ksmux

package module
v0.6.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 23, 2025 License: BSD-3-Clause Imports: 49 Imported by: 6

README

KSMUX

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

Tracing

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

// Enable tracing with default Jaeger endpoint
ksmux.ConfigureExport("", ksmux.ExportTypeJaeger)

// Or use Tempo
ksmux.ConfigureExport(ksmux.DefaultTempoEndpoint, ksmux.ExportTypeTempo)

// Enable tracing with optional custom handler
ksmux.EnableTracing(&CustomTraceHandler{})

// Add tracing middleware to capture all requests
app.Use(ksmux.TracingMiddleware)

// Manual span creation
app.Get("/api", func(c *ksmux.Context) {
    // Create a span
    span, ctx := ksmux.StartSpan(c.Request.Context(), "operation-name")
    defer span.End()

    // Add tags
    span.SetTag("key", "value")

    // Set error if needed
    span.SetError(err)

    // Set status code
    span.SetStatusCode(200)

    // Use context for propagation
    doWork(ctx)
})
Custom Trace Handler
type CustomTraceHandler struct{}

func (h *CustomTraceHandler) HandleTrace(span *ksmux.Span) {
    // Access span information
    fmt.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 tracing
ksmux.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 memory
ksmux.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.

Basic Usage

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

package main

import "github.com/kamalshkeir/ksmux"

func main() {
    // Create a new router
    router := ksmux.New()

    // Define a route
    router.Get("/", func(c *ksmux.Context) {
        c.Text("Hello World!")
    })

    // Start the server
    router.Run(":8080")
}

Routing

KSMUX supports various routing patterns:

// Basic routes
router.Get("/users", handleUsers)
router.Post("/users", createUser)
router.Put("/users/:id", updateUser)
router.Delete("/users/:id", deleteUser)

// URL parameters
router.Get("/users/:id", func(c *ksmux.Context) {
    id := c.Param("id")
    c.Json(map[string]string{"id": id})
})

// Wildcards
router.Get("/files/*filepath", serveFiles)

Context Methods

The Context object provides many useful methods for handling requests and responses:

// Response methods
c.Text("Hello")                    // Send plain text
c.Json(data)                       // Send JSON
c.JsonIndent(data)                 // Send indented JSON
c.Html("template.html", data)      // Render HTML template
c.Stream("message")                // Server-sent events
c.Download(bytes, "file.txt")      // Force download
c.Redirect("/new-path")            // HTTP redirect

// Request data
c.Param("id")                      // URL parameter
c.QueryParam("q")                  // Query parameter
c.BodyJson()                       // Parse JSON body
c.BodyStruct(&data)                // Parse body into struct
c.GetCookie("session")             // Get cookie value
c.SetCookie("session", "value")    // Set cookie

// Headers
c.SetHeader("X-Custom", "value")
c.AddHeader("X-Custom", "value")
c.SetStatus(200)

// Files
c.SaveFile(fileHeader, "path")     // Save uploaded file
c.ServeFile("image/png", "path")   // Serve local file

Middleware

Add middleware globally or to specific routes:

// Global middleware
router.Use(ksmux.Logs())
router.Use(ksmux.Gzip())
router.Use(ksmux.Cors())

// Route-specific middleware
router.Get("/admin", adminOnly(handleAdmin))

func adminOnly(next ksmux.Handler) ksmux.Handler {
    return func(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 WebSocket
    conn, err := c.UpgradeConnection()
    if err != nil {
        return
    }

    // Handle WebSocket messages
    for {
        messageType, p, err := conn.ReadMessage()
        if err != nil {
            return
        }

        // Echo the message back
        err = conn.WriteMessage(messageType, p)
        if err != nil {
            return
        }
    }
})

Templates

Render HTML templates with custom functions:

// Load templates
router.LocalTemplates("templates/")
// or
router.EmbededTemplates(embededFS, "templates/")

// Add custom template functions
router.NewTemplateFunc("upper", strings.ToUpper)

// Render template
router.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 directory
router.LocalStatics("static/", "/static")

// Serve embedded files
router.EmbededStatics(embededFS, "static/", "/static")

Load Balancer

func main() {
	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 servers
	err = 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 timeouts
ksmux.READ_TIMEOUT = 10 * time.Second  
ksmux.WRITE_TIMEOUT = 10 * time.Second
ksmux.IDLE_TIMEOUT = 30 * time.Second

// Cookie settings
ksmux.COOKIES_HttpOnly = true
ksmux.COOKIES_SECURE = true
ksmux.COOKIES_SameSite = http.SameSiteStrictMode
ksmux.COOKIES_Expires = 24 * time.Hour

License

BSD 3-Clause License. See LICENSE 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 ⭐️

Documentation

Index

Constants

View Source
const (
	StateClosed = iota
	StateOpen
	StateHalfOpen
)
View Source
const (
	// Export types
	ExportTypeJaeger    ExportType = "jaeger"
	ExportTypeTempo     ExportType = "tempo"
	ExportTypeZipkin    ExportType = "zipkin"
	ExportTypeDatadog   ExportType = "datadog"
	ExportTypeNewRelic  ExportType = "newrelic"
	ExportTypeHoneycomb ExportType = "honeycomb"
	ExportTypeOTLP      ExportType = "otlp"   // OpenTelemetry Protocol
	ExportTypeSignoz    ExportType = "signoz" // Open source alternative

	// Default endpoints
	DefaultJaegerEndpoint    = "http://localhost:14268/api/traces"
	DefaultTempoEndpoint     = "http://localhost:9411/api/v2/spans"
	DefaultZipkinEndpoint    = "http://localhost:9411/api/v2/spans"
	DefaultDatadogEndpoint   = "https://trace.agent.datadoghq.com"
	DefaultNewRelicEndpoint  = "https://trace-api.newrelic.com/trace/v1"
	DefaultHoneycombEndpoint = "https://api.honeycomb.io/1/traces"
	DefaultOTLPEndpoint      = "http://localhost:4318/v1/traces"
	DefaultSignozEndpoint    = "http://localhost:4318/v1/traces"

	// DefaultMaxTraces is the default maximum number of traces to keep in memory
	DefaultMaxTraces = 500
)

Variables

View Source
var (

	// docs
	DocsOutJson           = "."
	DocsEntryFile         = "ksmuxdocs/ksmuxdocs.go"
	OnDocsGenerationReady = func() {}
	// ctx cookies
	COOKIES_Expires  = 24 * 7 * time.Hour
	COOKIES_SameSite = http.SameSiteStrictMode
	COOKIES_HttpOnly = true
	COOKIES_SECURE   = true
)
View Source
var AutoCertRegexHostPolicy = false
View Source
var Cors = func(allowed ...string) func(http.Handler) http.Handler {
	firstRouter.state.corsEnabled = true
	if len(allowed) == 0 {
		allowed = append(allowed, "*")
	}
	for i := range allowed {
		if allowed[i] == "*" {
			continue
		}
		allowed[i] = strings.ReplaceAll(allowed[i], "localhost", "127.0.0.1")
		if !strings.HasPrefix(allowed[i], "http") {
			allowed[i] = "http://" + allowed[i]
		}
	}
	return func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if allowed[0] == "*" {
				w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
			} else {
				w.Header().Set("Access-Control-Allow-Origin", allowed[0])
			}
			w.Header().Set("Access-Control-Allow-Methods", "*")
			w.Header().Set("Access-Control-Allow-Credentials", "true")
			w.Header().Set("Access-Control-Allow-Headers", "*")
			if r.Method == "OPTIONS" {
				w.Header().Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, X-Korm, Authorization, Token, X-Token")
				w.WriteHeader(http.StatusNoContent)
				return
			}

			h.ServeHTTP(w, r)
		})
	}
}
View Source
var DocsGeneralDefaults = DocsGeneralInfo{
	Title:          "Korm Api Documentation",
	Version:        "1.0.0",
	Host:           "localhost:9313",
	BasePath:       "/",
	Description:    "Swagger Api Documentation for Korm",
	TermsOfService: "http://swagger.io/terms/",
	ContactName:    "API Support",
	ContactUrl:     "https://kamalshkeir.dev",
	ContactEmail:   "support@email.com",
	LicenseName:    "Apache 2.0",
	LicenseUrl:     "http://www.apache.org/licenses/LICENSE-2.0.html",
}
View Source
var MatchedRoutePathParam = "$ksmuxdone"

MatchedRoutePathParam is the Param name under which the path of the matched route is stored, if Router.SaveMatchedPath is set.

Functions

func BeforeRenderHtml

func BeforeRenderHtml(uniqueName string, fn func(c *Context, data *map[string]any))

BeforeRenderHtml executed before every html render, you can use reqCtx.Value(key).(type.User) for example and add data to templates globaly

func CheckAndInstallSwagger

func CheckAndInstallSwagger() error

func ClearTraces added in v0.4.3

func ClearTraces()

ClearTraces clears all recorded traces

func ConfigureExport added in v0.4.3

func ConfigureExport(endpoint string, exportType ExportType)

ConfigureExport sets the export endpoint and type

func CopyFile added in v0.2.2

func CopyFile(src, dst string, BUFFERSIZE int64) error

func DisableTracing added in v0.4.3

func DisableTracing()

DisableTracing disables tracing

func EnableTracing added in v0.4.3

func EnableTracing(handler TraceHandler)

EnableTracing enables tracing with an optional custom handler

func ExecuteRawHtml

func ExecuteRawHtml(rawTemplateName string, data map[string]any) (string, error)

func GenerateGoDocsComments

func GenerateGoDocsComments(pkgName ...string)

func GenerateID added in v0.4.3

func GenerateID() string

GenerateID generates a unique ID for traces and spans

func GenerateJsonDocs

func GenerateJsonDocs(entryDocsFile ...string)

func GenerateUUID

func GenerateUUID() (string, error)

func GetPrivateIp

func GetPrivateIp() string

func GetRouters added in v0.5.5

func GetRouters() *kmap.SafeMap[string, *Router]

func GetTraces added in v0.4.3

func GetTraces() map[string][]*Span

GetTraces returns all recorded traces

func Graceful

func Graceful(f func() error) error

func Gzip

func Gzip() func(http.Handler) http.Handler

func IgnoreLogsEndpoints added in v0.0.5

func IgnoreLogsEndpoints(pathContain ...string)

func IgnoreTracingEndpoints added in v0.4.3

func IgnoreTracingEndpoints(pathContain ...string)

IgnoreTracingEndpoints allows adding paths to ignore in tracing

func IsSupervisor added in v0.6.8

func IsSupervisor() bool

IsSupervisor returns true if current process is the supervisor

func Limiter added in v0.0.7

func Limiter(conf *ConfigLimiter) func(http.Handler) http.Handler

func Logs

func Logs(callback ...func(method, path, remote string, status int, took time.Duration)) func(http.Handler) http.Handler

func NewFuncMap added in v0.0.6

func NewFuncMap(funcMap map[string]any)

func SaveMultipartFile

func SaveMultipartFile(fh *multipart.FileHeader, path string) (err error)

SaveMultipartFile Save MultipartFile

func SaveRawHtml

func SaveRawHtml(templateRaw string, templateName string)

SaveRawHtml save templateRaw as templateName to be able to use it like c.RawHtml

func SetMaxTraces added in v0.4.4

func SetMaxTraces(max int)

SetMaxTraces sets the maximum number of traces to keep in memory

func SetSSLEmail added in v0.2.2

func SetSSLEmail(email string)

func SetSSLMode added in v0.2.2

func SetSSLMode(ProdOrDev string)

func SliceContains

func SliceContains[T comparable](elems []T, vs ...T) bool

func StringContains

func StringContains(s string, subs ...string) bool

func ToSlug

func ToSlug(s string) (string, error)

func TracingMiddleware added in v0.4.3

func TracingMiddleware(next http.Handler) http.Handler

TracingMiddleware adds tracing to all routes

func UpgradeConnection

func UpgradeConnection(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*ws.Conn, error)

Types

type Backend added in v0.5.3

type Backend struct {
	URL   *url.URL
	Alive bool

	ReverseProxy *httputil.ReverseProxy
	FailureCount int32
	LastChecked  time.Time

	Middlewares []Handler
	// contains filtered or unexported fields
}

type BackendOpt added in v0.5.3

type BackendOpt struct {
	Url         string
	Middlewares []Handler
}

type CircuitBreaker added in v0.5.3

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

func NewCircuitBreaker added in v0.5.3

func NewCircuitBreaker() *CircuitBreaker

func (*CircuitBreaker) IsAvailable added in v0.5.3

func (cb *CircuitBreaker) IsAvailable() bool

func (*CircuitBreaker) RecordFailure added in v0.5.3

func (cb *CircuitBreaker) RecordFailure()

func (*CircuitBreaker) RecordSuccess added in v0.5.3

func (cb *CircuitBreaker) RecordSuccess()

type Config added in v0.5.5

type Config struct {
	Address     string
	Domain      string
	SubDomains  []string
	CertPath    string
	CertKeyPath string
	MediaDir    string
	// contains filtered or unexported fields
}

type ConfigLimiter added in v0.0.7

type ConfigLimiter struct {
	Message        string           // default "TOO MANY REQUESTS"
	RateEvery      time.Duration    // default 10 min
	BurstsN        int              // default 100
	CheckEvery     time.Duration    // default 5 min
	BlockDuration  time.Duration    // default 10 min
	OnLimitReached func(c *Context) // Custom handler for when limit is reached
	Strategy       LimitStrategy    // Strategy for rate limiting
	HeaderName     string           // Header name for LimitByHeader strategy
	PathConfigs    []PathConfig     // Path-specific configurations
}

type Context

type Context struct {
	http.ResponseWriter
	*http.Request
	Params Params
	// contains filtered or unexported fields
}

func (*Context) AddHeader

func (c *Context) AddHeader(key, value string)

AddHeader Add append a header value to key if exist

func (*Context) AddSSEHeaders added in v0.0.4

func (c *Context) AddSSEHeaders()

func (*Context) BindBody

func (c *Context) BindBody(strctPointer any, isXML ...bool) error

BindBody scans body to struct, default json

func (*Context) BodyJson

func (c *Context) BodyJson() map[string]any

BodyJson get json body from request and return map

func (*Context) BodyStruct added in v0.3.1

func (c *Context) BodyStruct(dest any) error

BodyStruct decodes request body into struct

func (*Context) BodyText

func (c *Context) BodyText() string

func (*Context) Context

func (c *Context) Context() context.Context

Context return request context

func (*Context) DeleteCookie

func (c *Context) DeleteCookie(key string)

DeleteCookie delete cookie with specific key

func (*Context) DeleteFile

func (c *Context) DeleteFile(path string) error

DELETE FILE

func (*Context) Download

func (c *Context) Download(data_bytes []byte, asFilename string)

Download download data_bytes(content) asFilename(test.json,data.csv,...) to the client

func (*Context) EarlyHint added in v0.2.6

func (c *Context) EarlyHint(hints ...EarlyHint)

func (*Context) Error

func (c *Context) Error(errorMsg any)

func (*Context) Flush

func (c *Context) Flush() bool

func (*Context) GetCookie

func (c *Context) GetCookie(key string) (string, error)

GetCookie get cookie with specific key

func (*Context) GetKey

func (c *Context) GetKey(key string) (any, bool)

GetKey return request context value for given key

func (*Context) GetKeyAs added in v0.3.1

func (c *Context) GetKeyAs(key string, ptrStruct any) bool

GetKeyAs return request context value for given key

func (*Context) GetUserIP

func (c *Context) GetUserIP() string

func (*Context) Html

func (c *Context) Html(template_name string, data map[string]any)

Html return template_name with data to the client

func (*Context) IsAuthenticated

func (c *Context) IsAuthenticated(key ...string) bool

func (*Context) Json

func (c *Context) Json(data any)

Json return json to the client

func (*Context) JsonIndent

func (c *Context) JsonIndent(data any)

JsonIndent return json indented to the client

func (*Context) MatchedPath

func (c *Context) MatchedPath() string

func (*Context) NamedRawHtml

func (c *Context) NamedRawHtml(rawTemplateName string, data map[string]any) error

NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler

func (*Context) Param

func (c *Context) Param(name string) string

func (*Context) ParseMultipartForm

func (c *Context) ParseMultipartForm(maxSize ...int64) (formData url.Values, formFiles map[string][]*multipart.FileHeader)

func (*Context) QueryParam

func (c *Context) QueryParam(name string) string

QueryParam get query param

func (*Context) RawHtml

func (c *Context) RawHtml(rawTemplate string, data map[string]any) error

NamedRawHtml render rawTemplateName with data using go engine, make sure to save the html using ksmux.SaveRawHtml outside the handler

func (*Context) Redirect

func (c *Context) Redirect(path string)

Redirect redirect the client to the specified path with a custom code, default status 307

func (*Context) Return added in v0.3.3

func (c *Context) Return(kvs ...any)

func (*Context) SaveFile

func (c *Context) SaveFile(fileheader *multipart.FileHeader, path string) error

SaveFile save file to path

func (*Context) ServeEmbededFile

func (c *Context) ServeEmbededFile(content_type string, embed_file []byte)

ServeEmbededFile serve an embeded file from handler

func (*Context) ServeFile

func (c *Context) ServeFile(content_type, path_to_file string)

ServeFile serve a file from handler

func (*Context) SetCookie

func (c *Context) SetCookie(key, value string, maxAge ...time.Duration)

SetCookie set cookie given key and value

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader Set the header value to the new value, old removed

func (*Context) SetKey

func (c *Context) SetKey(key string, value any)

func (*Context) SetStatus

func (c *Context) SetStatus(statusCode int)

SetHeader Set the header value to the new value, old removed

func (*Context) SliceParams

func (c *Context) SliceParams() Params

func (*Context) Status

func (c *Context) Status(code int) *Context

Status set status to context, will not be writed to header

func (*Context) Stream

func (c *Context) Stream(response string) error

Stream send SSE Streaming Response

func (*Context) Success added in v0.3.2

func (c *Context) Success(successMsg any)

func (*Context) Text

func (c *Context) Text(body string)

Text return text with custom code to the client

func (*Context) UpgradeConnection added in v0.0.4

func (c *Context) UpgradeConnection() (*ws.Conn, error)

func (*Context) UploadFile

func (c *Context) UploadFile(received_filename, folder_out string, acceptedFormats ...string) (string, []byte, error)

UploadFile upload received_filename into folder_out and return url,fileByte,error

func (*Context) UploadFiles

func (c *Context) UploadFiles(received_filenames []string, folder_out string, acceptedFormats ...string) ([]string, [][]byte, error)

func (*Context) User

func (c *Context) User(key ...string) (any, bool)

User is alias of c.Keys but have key default to 'user'

func (*Context) WithPushOptions added in v0.1.3

func (c *Context) WithPushOptions(opts *http.PushOptions)

type ContextKey

type ContextKey string

type DocsGeneralInfo

type DocsGeneralInfo struct {
	Title          string
	Version        string
	Host           string
	BasePath       string
	Description    string
	TermsOfService string
	ContactName    string
	ContactUrl     string
	ContactEmail   string
	LicenseName    string
	LicenseUrl     string
}

type DocsIn

type DocsIn struct {
	Name        string
	In          string
	Type        string
	Required    bool
	Description string
}

func (DocsIn) String

func (dp DocsIn) String() string

type DocsOut

type DocsOut struct {
	StatusCode        string
	TypeObjectOrArray string
	TypePath          string
	Value             string
	Extra             string
}

func (DocsOut) String

func (dr DocsOut) String() string

type DocsRoute

type DocsRoute struct {
	Method           string
	Summary          string
	Description      string
	Tags             string
	Accept           string
	Produce          string
	Response         string
	FailureResponses []string
	Params           []string
	Pattern          string
	Triggered        bool
}

type EarlyHint added in v0.2.6

type EarlyHint struct {
	Type EarlyHintType
	URL  string
	Rel  string
}

type EarlyHintType added in v0.2.6

type EarlyHintType string
var (
	EarlyHint_OBJECT   EarlyHintType = "object"
	EarlyHint_IMAGE    EarlyHintType = "image"
	EarlyHint_AUDIO    EarlyHintType = "audio"
	EarlyHint_TRACK    EarlyHintType = "track"
	EarlyHint_VIDEO    EarlyHintType = "video"
	EarlyHint_DOCUMENT EarlyHintType = "document"
	EarlyHint_EMBED    EarlyHintType = "embed"
	EarlyHint_STYLE    EarlyHintType = "style"
	EarlyHint_SCRIPT   EarlyHintType = "script"
	EarlyHint_FETCH    EarlyHintType = "fetch"
	EarlyHint_FONT     EarlyHintType = "font"
	EarlyHint_WORKER   EarlyHintType = "worker"
)

type ExportType added in v0.4.3

type ExportType string

ExportType defines the type of trace exporter

type GroupRouter

type GroupRouter struct {
	*Router
	Group string
	// contains filtered or unexported fields
}

func (*GroupRouter) Delete

func (gr *GroupRouter) Delete(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Get

func (gr *GroupRouter) Get(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Head

func (gr *GroupRouter) Head(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Options

func (gr *GroupRouter) Options(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Patch

func (gr *GroupRouter) Patch(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Post

func (gr *GroupRouter) Post(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Put

func (gr *GroupRouter) Put(pattern string, handler Handler, origines ...string) *Route

func (*GroupRouter) Use

func (gr *GroupRouter) Use(middlewares ...func(Handler) Handler)

Use chain handler middlewares

type Handler

type Handler func(c *Context)

Handler is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (path variables).

func BasicAuth

func BasicAuth(ksmuxHandlerFunc Handler, user, pass string) Handler

func (Handler) ServeHTTP

func (handler Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

type LimitStrategy added in v0.5.3

type LimitStrategy int

LimitStrategy defines how we identify requests for rate limiting

const (
	LimitByIP LimitStrategy = iota
	LimitByPath
	LimitByHeader
	LimitByIPAndPath
)

type LoadBalancer added in v0.5.3

type LoadBalancer struct {
	// contains filtered or unexported fields
}

func (*LoadBalancer) AddBackend added in v0.5.3

func (lb *LoadBalancer) AddBackend(rawURL string, mid ...Handler) error

func (*LoadBalancer) NextBackend added in v0.5.3

func (lb *LoadBalancer) NextBackend(path string) *Backend

Round Robin Selection

func (*LoadBalancer) RemoveDeadBackends added in v0.5.5

func (lb *LoadBalancer) RemoveDeadBackends()

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func GetParamsFromCtx

func GetParamsFromCtx(ctx context.Context) Params

GetParamsFromCtx get params from ctx for http.Handler

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

type PathConfig added in v0.5.3

type PathConfig struct {
	Pattern   string        // Path pattern to match (supports wildcards with *)
	RateEvery time.Duration // Rate limit for this path
	BurstsN   int           // Burst limit for this path
}

type Route

type Route struct {
	Method   string
	Pattern  string
	Origines string
	Handler  Handler
	Docs     *DocsRoute
}

func (*Route) Accept

func (r *Route) Accept(accept string) *Route

Accept set docs accept, default 'json'

func (*Route) Description

func (r *Route) Description(description string) *Route

func (*Route) In

func (r *Route) In(docsParam ...string) *Route

In must be like "name in typePath required 'desc'" or you can use ksmux.DocsIn.String() method

func (*Route) Out

func (r *Route) Out(sucessResponse string, failureResponses ...string) *Route

Out must be like "200 {object}/{array}/{string} app1.Account/string 'okifstring'" or you can use ksmux.DocsOut.String() method

func (*Route) Produce

func (r *Route) Produce(produce string) *Route

Produce set docs produce, default 'json'

func (*Route) Summary

func (r *Route) Summary(summary string) *Route

func (*Route) Tags

func (r *Route) Tags(tags ...string) *Route

type Router

type Router struct {
	Server          *http.Server
	AutoCertManager *autocert.Manager
	Config          *Config
	RouterConfig    *RouterConfig
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func GetFirstRouter added in v0.5.5

func GetFirstRouter() *Router

func GetRouter added in v0.5.5

func GetRouter(addrOrDomain string) (*Router, bool)

func New

func New(config ...Config) *Router

New returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) Address added in v0.5.5

func (router *Router) Address() string

func (*Router) CreateServerCerts added in v0.2.2

func (router *Router) CreateServerCerts(domainName string, subDomains ...string) (*autocert.Manager, *tls.Config)

func (*Router) Delete

func (r *Router) Delete(path string, handler Handler, origines ...string) *Route

Delete is a shortcut for router.Handle(http.MethodDelete, path, handler)

func (*Router) EmbededStatics

func (router *Router) EmbededStatics(embeded embed.FS, pathLocalDir, webPath string, handlerMiddlewares ...func(handler Handler) Handler) error

func (*Router) EmbededTemplates

func (router *Router) EmbededTemplates(template_embed embed.FS, rootDir string) error

func (*Router) EnableDomainCheck added in v0.0.3

func (router *Router) EnableDomainCheck()

EnableDomainCheck enable only the domain check from ksmux methods Get,Post,... (does not add cors middleware)

func (*Router) Get

func (r *Router) Get(path string, handler Handler, origines ...string) *Route

Get is a shortcut for router.Handle(http.MethodGet, path, handler)

func (*Router) Group

func (router *Router) Group(prefix string) *GroupRouter

Group create group path

func (*Router) Handle

func (r *Router) Handle(method, path string, handler Handler, origines ...string) *Route

Handle registers a new request handler with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc, origines ...string) *Route

HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handler.

func (*Router) Head

func (r *Router) Head(path string, handler Handler, origines ...string) *Route

Head is a shortcut for router.Handle(http.MethodHead, path, handler)

func (*Router) Host added in v0.5.5

func (router *Router) Host() string

func (*Router) IsTls added in v0.5.5

func (router *Router) IsTls() bool

func (*Router) LoadBalancer added in v0.5.3

func (router *Router) LoadBalancer(pattern string, backends ...BackendOpt) error

func (*Router) LocalStatics

func (router *Router) LocalStatics(dirPath, webPath string, handlerMiddlewares ...func(handler Handler) Handler) error

func (*Router) LocalTemplates

func (router *Router) LocalTemplates(pathToDir string) error

func (*Router) Lookup

func (r *Router) Lookup(method, path string) (Handler, Params, bool, string)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handler function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) NewFuncMap

func (router *Router) NewFuncMap(funcMap map[string]any)

func (*Router) NewTemplateFunc

func (router *Router) NewTemplateFunc(funcName string, function any)

func (*Router) OnShutdown added in v0.5.5

func (router *Router) OnShutdown(fn func() error)

func (*Router) Options

func (r *Router) Options(path string, handler Handler, origines ...string) *Route

Options is a shortcut for router.Handle(http.MethodOptions, path, handler)

func (*Router) Patch

func (r *Router) Patch(path string, handler Handler, origines ...string) *Route

Patch is a shortcut for router.Handle(http.MethodPatch, path, handler)

func (*Router) Port added in v0.5.5

func (router *Router) Port() string

func (*Router) Post

func (r *Router) Post(path string, handler Handler, origines ...string) *Route

Post is a shortcut for router.Handle(http.MethodPost, path, handler)

func (*Router) PrintTree added in v0.3.9

func (r *Router) PrintTree()

func (*Router) Put

func (r *Router) Put(path string, handler Handler, origines ...string) *Route

Put is a shortcut for router.Handle(http.MethodPut, path, handler)

func (*Router) Restart added in v0.5.5

func (router *Router) Restart(cleanupCallbacks ...func() error) error

Restart shuts down the current server and lets supervisor start a new instance

func (*Router) ReverseProxy

func (router *Router) ReverseProxy(host, toURL string) (newRouter *Router)

func (*Router) Run

func (router *Router) Run()

Run HTTP server on address

func (*Router) RunAutoTLS

func (router *Router) RunAutoTLS()

RunAutoTLS HTTPS server generate certificates and handle renew

func (*Router) RunTLS

func (router *Router) RunTLS()

RunTLS HTTPS server using certificates

func (*Router) ServeEmbededFile

func (router *Router) ServeEmbededFile(file []byte, endpoint, contentType string)

func (*Router) ServeFiles

func (r *Router) ServeFiles(path string, root http.FileSystem)

ServeFiles serves files from the given file system root. The path must end with "/*filepath", files are then served from the local path /defined/root/dir/*filepath. For example if root is "/etc" and *filepath is "passwd", the local file "/etc/passwd" would be served. Internally a http.FileServer is used, therefore http.NotFound is used instead of the Router's NotFound handler. To use the operating system's file system implementation, use http.Dir:

router.ServeFiles("/src/*filepath", http.Dir("/var/www"))

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

func (*Router) ServeLocalFile

func (router *Router) ServeLocalFile(file, endpoint, contentType string)

func (*Router) Signal added in v0.5.6

func (router *Router) Signal() chan os.Signal

func (*Router) Stop added in v0.5.6

func (router *Router) Stop()

Stop gracefully shuts down the server. It triggers the shutdown process by sending an interrupt signal and waits for completion.

func (*Router) ToMap added in v0.3.9

func (r *Router) ToMap() map[string]*node

ToMap returns a map of all registered paths and their node

func (*Router) Use

func (router *Router) Use(midws ...func(http.Handler) http.Handler)

Use chain global router middlewares

func (*Router) WithDocs

func (router *Router) WithDocs(genJsonDocs bool, genGoDocs ...bool) *Router

WithDocs check and install swagger, and generate json and go docs at the end , after the server run, you can use ksmux.OnDocsGenerationReady() genGoDocs default to true if genJsonDocs

func (*Router) WithMetrics

func (router *Router) WithMetrics(httpHandler http.Handler, path ...string)

WithMetrics take prometheus handler and serve metrics on path or default /metrics

func (*Router) WithPprof

func (router *Router) WithPprof(path ...string)

WithPprof enable std library pprof at /debug/pprof, prefix default to 'debug'

type RouterConfig added in v0.5.5

type RouterConfig struct {
	ReadTimeout      time.Duration
	WriteTimeout     time.Duration
	IdleTimeout      time.Duration
	GlobalOPTIONS    http.Handler
	NotFound         http.Handler
	MethodNotAllowed http.Handler
	PanicHandler     func(http.ResponseWriter, *http.Request, interface{})

	SaveMatchedPath        bool
	RedirectTrailingSlash  bool
	RedirectFixedPath      bool
	HandleMethodNotAllowed bool
	HandleOPTIONS          bool
	// contains filtered or unexported fields
}

type Span added in v0.4.3

type Span struct {
	// contains filtered or unexported fields
}

Span represents a single operation within a trace

func StartSpan added in v0.4.3

func StartSpan(ctx context.Context, name string) (*Span, context.Context)

StartSpan creates a new span

func (*Span) Duration added in v0.4.3

func (s *Span) Duration() time.Duration

func (*Span) End added in v0.4.3

func (s *Span) End()

EndSpan ends a span and records it

func (*Span) EndTime added in v0.4.3

func (s *Span) EndTime() time.Time

func (*Span) Error added in v0.4.3

func (s *Span) Error() error

func (*Span) Name added in v0.4.3

func (s *Span) Name() string

func (*Span) ParentID added in v0.4.3

func (s *Span) ParentID() string

func (*Span) SetDuration added in v0.4.5

func (s *Span) SetDuration(d time.Duration)

SetStatusCode sets the HTTP status code

func (*Span) SetError added in v0.4.3

func (s *Span) SetError(err error)

SetError sets an error on the span

func (*Span) SetStatusCode added in v0.4.3

func (s *Span) SetStatusCode(code int)

SetStatusCode sets the HTTP status code

func (*Span) SetTag added in v0.4.3

func (s *Span) SetTag(key, value string)

SetTag adds a tag to the span

func (*Span) SpanID added in v0.4.3

func (s *Span) SpanID() string

func (*Span) StartTime added in v0.4.3

func (s *Span) StartTime() time.Time

func (*Span) StatusCode added in v0.4.3

func (s *Span) StatusCode() int

func (*Span) Tags added in v0.4.3

func (s *Span) Tags() map[string]string

func (*Span) TraceID added in v0.4.3

func (s *Span) TraceID() string

Getter methods

type StatusRecorder

type StatusRecorder struct {
	http.ResponseWriter
	Status int
}

func (*StatusRecorder) Flush

func (r *StatusRecorder) Flush()

func (*StatusRecorder) Hijack

func (r *StatusRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error)

func (*StatusRecorder) WriteHeader

func (r *StatusRecorder) WriteHeader(status int)

type TraceHandler added in v0.4.3

type TraceHandler interface {
	HandleTrace(span *Span)
}

TraceHandler is an interface for custom trace handling

type Tracer added in v0.4.3

type Tracer struct {
	// contains filtered or unexported fields
}

Tracer handles the creation and management of traces

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL