- Notifications
You must be signed in to change notification settings - Fork1
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
kamalshkeir/ksmux
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
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.
- 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.
To install KSMUX, use the following command:
go get github.com/kamalshkeir/ksmux@latest
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()}
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)})
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())}
The tracer can export to any OpenTelemetry-compatible backend. Pre-configured support for:
- Jaeger (default)
- Grafana Tempo
Default endpoints:
// Add paths to ignore in tracingksmux.IgnoreTracingEndpoints("/health","/metrics")
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.
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)
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
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) }}
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 } }})
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, })})
Serve static files from local or embedded sources:
// Serve local directoryrouter.LocalStatics("static/","/static")// Serve embedded filesrouter.EmbededStatics(embededFS,"static/","/static")
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")}
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
BSD 3-Clause License. SeeLICENSE for details.
Contributions are welcome! Please feel free to submit a Pull Request.
Kamal SHKEIR
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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Uh oh!
There was an error while loading.Please reload this page.