Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

KSMUX is a fast and lightweight HTTP router and web framework for Go, featuring built-in WebSocket support. It is designed to be simple yet powerful, providing a range of features to build modern web applications.

License

NotificationsYou must be signed in to change notification settings

kamalshkeir/ksmux

Repository files navigation

KSMUX is a fast and lightweight HTTP router and web framework for Go, featuring built-in WebSocket support. It is designed to be simple yet powerful, providing a range of features to build modern web applications.

Features

  • Fast HTTP Routing: Supports URL parameters and wildcards for flexible routing.
  • WebSocket Support: Built-in support for WebSocket connections with optional compression.
  • Middleware Support: Easily add middleware for request handling.
  • Static File Serving: Serve static files from local or embedded sources.
  • Template Rendering: Render HTML templates with custom functions.
  • GZIP Compression: Automatic GZIP compression for responses.
  • Basic Authentication: Simple basic authentication middleware.
  • CORS Support: Cross-Origin Resource Sharing (CORS) middleware.
  • Request Logging: Log incoming requests with customizable logging.
  • Rate Limiting: Limit the rate of incoming requests.
  • Proxy Support: Reverse proxy capabilities.
  • Load Balancer: powerful load balancer that support middlewares as code for each backend
  • Server-Sent Events (SSE): Support for server-sent events.
  • Built-in Tracing: Distributed tracing with OpenTelemetry-compatible backends.

Installation

To install KSMUX, use the following command:

go get github.com/kamalshkeir/ksmux@latest

Basic Usage

Here's a simple example to get started with KSMUX:

package mainimport"github.com/kamalshkeir/ksmux"funcmain() {// Create a new routerrouter:=ksmux.New(ksmux.Confif{Address:"localhost:9313",    })// Define a routerouter.Get("/",func(c*ksmux.Context) {c.Text("Hello World!")    })// Start the serverrouter.Run()}

Tracing

KSMUX includes built-in distributed tracing capabilities that can export to OpenTelemetry-compatible backends:

// Enable tracing with default Jaeger endpointksmux.ConfigureExport("",ksmux.ExportTypeJaeger)// Or use Tempoksmux.ConfigureExport(ksmux.DefaultTempoEndpoint,ksmux.ExportTypeTempo)// Enable tracing with optional custom handlerksmux.EnableTracing(&CustomTraceHandler{})// Add tracing middleware to capture all requestsapp.Use(ksmux.TracingMiddleware)// Manual span creationapp.Get("/api",func(c*ksmux.Context) {// Create a spanspan,ctx:=ksmux.StartSpan(c.Request.Context(),"operation-name")deferspan.End()// Add tagsspan.SetTag("key","value")// Set error if neededspan.SetError(err)// Set status codespan.SetStatusCode(200)// Use context for propagationdoWork(ctx)})

Custom Trace Handler

typeCustomTraceHandlerstruct{}func (h*CustomTraceHandler)HandleTrace(span*ksmux.Span) {// Access span informationfmt.Printf("Trace: %s, Span: %s, Operation: %s\n",span.TraceID(),span.SpanID(),span.Name())}

Supported Backends

The tracer can export to any OpenTelemetry-compatible backend. Pre-configured support for:

  • Jaeger (default)
  • Grafana Tempo

Default endpoints:

Ignore Paths

// Add paths to ignore in tracingksmux.IgnoreTracingEndpoints("/health","/metrics")

Memory Management

By default, the tracer keeps the last 1000 traces in memory. You can adjust this limit:

// Set maximum number of traces to keep in memoryksmux.SetMaxTraces(500)// Keep only the last 500 traces

When the limit is reached, the oldest trace will be removed when a new one is added.

Routing

KSMUX supports various routing patterns:

// Basic routesrouter.Get("/users",handleUsers)router.Post("/users",createUser)router.Put("/users/:id",updateUser)router.Delete("/users/:id",deleteUser)// URL parametersrouter.Get("/users/:id",func(c*ksmux.Context) {id:=c.Param("id")c.Json(map[string]string{"id":id})})// Wildcardsrouter.Get("/files/*filepath",serveFiles)

Context Methods

TheContext object provides many useful methods for handling requests and responses:

// Response methodsc.Text("Hello")// Send plain textc.Json(data)// Send JSONc.JsonIndent(data)// Send indented JSONc.Html("template.html",data)// Render HTML templatec.Stream("message")// Server-sent eventsc.Download(bytes,"file.txt")// Force downloadc.Redirect("/new-path")// HTTP redirect// Request datac.Param("id")// URL parameterc.QueryParam("q")// Query parameterc.BodyJson()// Parse JSON bodyc.BodyStruct(&data)// Parse body into structc.GetCookie("session")// Get cookie valuec.SetCookie("session","value")// Set cookie// Headersc.SetHeader("X-Custom","value")c.AddHeader("X-Custom","value")c.SetStatus(200)// Filesc.SaveFile(fileHeader,"path")// Save uploaded filec.ServeFile("image/png","path")// Serve local file

Middleware

Add middleware globally or to specific routes:

// Global middlewarerouter.Use(ksmux.Logs())router.Use(ksmux.Gzip())router.Use(ksmux.Cors())// Route-specific middlewarerouter.Get("/admin",adminOnly(handleAdmin))funcadminOnly(next ksmux.Handler) ksmux.Handler {returnfunc(c*ksmux.Context) {if!isAdmin(c) {c.Status(403).Text("Forbidden")return        }next(c)    }}

WebSocket Support

KSMUX provides built-in support for WebSocket connections:

router.Get("/ws",func(c*ksmux.Context) {// Upgrade HTTP connection to WebSocketconn,err:=c.UpgradeConnection()iferr!=nil {return    }// Handle WebSocket messagesfor {messageType,p,err:=conn.ReadMessage()iferr!=nil {return        }// Echo the message backerr=conn.WriteMessage(messageType,p)iferr!=nil {return        }    }})

Templates

Render HTML templates with custom functions:

// Load templatesrouter.LocalTemplates("templates/")// orrouter.EmbededTemplates(embededFS,"templates/")// Add custom template functionsrouter.NewTemplateFunc("upper",strings.ToUpper)// Render templaterouter.Get("/",func(c*ksmux.Context) {c.Html("index.html",map[string]any{"title":"Home","user":user,    })})

Static Files

Serve static files from local or embedded sources:

// Serve local directoryrouter.LocalStatics("static/","/static")// Serve embedded filesrouter.EmbededStatics(embededFS,"static/","/static")

Load Balancer

funcmain() {app:=ksmux.New()err:=app.LocalStatics("assets","/static")lg.CheckError(err)err=app.LocalTemplates("temps")lg.CheckError(err)// Setup load balancer for /api path, distributing requests between two backend serverserr=app.LoadBalancer("/",ksmux.BackendOpt{Url:"localhost:8081",Middlewares: []ksmux.Handler{func(c*ksmux.Context) {fmt.Println("from middleware 8081")},},},ksmux.BackendOpt{Url:"localhost:8082",},)lg.CheckError(err)app.Run(":9313")}

Configuration

Configure server settings and cookies:

// Server timeoutsksmux.READ_TIMEOUT=10*time.Secondksmux.WRITE_TIMEOUT=10*time.Secondksmux.IDLE_TIMEOUT=30*time.Second// Cookie settingsksmux.COOKIES_HttpOnly=trueksmux.COOKIES_SECURE=trueksmux.COOKIES_SameSite=http.SameSiteStrictModeksmux.COOKIES_Expires=24*time.Hour

License

BSD 3-Clause License. SeeLICENSE for details.

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Author

Kamal SHKEIR

Support

If you find this project helpful, please give it a ⭐️

About

KSMUX is a fast and lightweight HTTP router and web framework for Go, featuring built-in WebSocket support. It is designed to be simple yet powerful, providing a range of features to build modern web applications.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp