Documentation
¶
Overview ¶
Package midx provides HTTP middleware factories for httpx applications.
Each exported constructor returns a standard net/http middleware (or httpx.Middleware where noted). Compose them with httpx.ApplyMiddlewares so the first argument runs outermost on the request path.
Example:
h, err := routex.NewHandler(apis.R, "example")
if err != nil {
panic(err)
}
h = httpx.ApplyMiddlewares(
midx.InjectContext(user.Carry(user.New())),
midx.LogHandler(),
midx.DefaultCORS(),
)(h)
if err = confhttp.ListenAndServe(ctx, "0.0.0.0:9001", h); err != nil {
panic(err)
}
Middleware ¶
- InjectContext: compose contextx.Carrier values into request context before the handler runs.
- LogHandler: access logging with B3 trace propagation, optional span from httpx.OperationMetaFrom, and per-request level override via the x-enable-log-level header.
- MetricHandler: serve Prometheus metrics at /.sys/metrics.
- DefaultCORS / CORS: Cross-Origin Resource Sharing; DefaultCORS sets httpx-friendly defaults (methods, headers including Authorization, exposed rate-limit headers, credentials).
- CanonicalHost: redirect to a canonical host/scheme (from gorilla/handlers).
- DefaultCompress / Compress: gzip and brotli response compression when Accept-Encoding allows it.
- PProfHandler: optional net/http/pprof under /.sys/debug/pprof when enabled.
Internal packages ¶
Implementation details live under internal/; midx re-exports thin wrappers and functional options where applicable.
- logginghandler: [ResponseWriter] wrapper that records status, treats 4xx/5xx bodies as errors for logs, and [OmitAuthorization] for safe URL logging.
- corshandler: CORS header handling and preflight (from gorilla/handlers).
- canonicalhandler: host/scheme redirect handler (from gorilla/handlers).
- compresshandler: gzip/brotli encoding (from gorilla/handlers).
- pprofhandler: path-prefixed pprof endpoints under /.sys/debug/pprof.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/x/contextx"
"github.com/xoctopus/x/logx"
"github.com/xoctopus/httpx/internal/testutil"
"github.com/xoctopus/httpx/pkg/httpx"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
ctx := logx.With(context.Background(), logx.Discard())
userCtx := contextx.NewT[string]()
carriers := []contextx.Carrier{
userCtx.Carry("alice"),
}
base := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name, _ := userCtx.From(r.Context())
_, _ = fmt.Fprintln(w, name)
})
h := httpx.ApplyMiddlewares(
midx.InjectContext(carriers...),
midx.LogHandler(true),
midx.DefaultCORS(),
)(base)
req := httptest.NewRequest(http.MethodGet, "/hello", nil).WithContext(ctx)
req.Header.Set("Origin", "https://app.example")
rec := testutil.ServeHandler(h, req)
fmt.Println(rec.Code)
fmt.Println(rec.Body.String())
fmt.Println(rec.Header().Get("Access-Control-Allow-Origin"))
}
Output: 200 alice *
Index ¶
- Constants
- func CORS(opts ...CORSOption) func(http.Handler) http.Handler
- func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler
- func Compress(level int) func(h http.Handler) http.Handler
- func DefaultCORS(opts ...CORSOption) func(http.Handler) http.Handler
- func DefaultCompress() func(h http.Handler) http.Handler
- func DefaultLogHandler() func(http.Handler) http.Handler
- func ExtractBasicAttrs(req *http.Request) []attribute.KeyValue
- func ExtractRouteAttrs(status int, info *types.OperationMeta, req *http.Request) []attribute.KeyValue
- func InjectContext(carriers ...contextx.Carrier) httpx.Middleware
- func LogHandler(enableOTel bool) func(http.Handler) http.Handler
- func MetricHandler(gatherer prometheus.Gatherer) func(http.Handler) http.Handler
- func PProfHandler(enabled bool) func(handler http.Handler) http.Handler
- type CORSOption
- func AllowCredentials() CORSOption
- func AllowedHeaders(headers []string) CORSOption
- func AllowedMethods(methods []string) CORSOption
- func AllowedOriginValidator(fn OriginValidator) CORSOption
- func AllowedOrigins(origins []string) CORSOption
- func ExposedHeaders(headers []string) CORSOption
- func IgnoreOptions() CORSOption
- func MaxAge(age int) CORSOption
- func OptionStatusCode(code int) CORSOption
- type OriginValidator
Examples ¶
Constants ¶
const ( LogKeyClientAddress = string(semconv.ClientAddressKey) LogKeyRequestMethod = string(semconv.HTTPRequestMethodKey) LogKeyProtocolVersion = string(semconv.NetworkProtocolVersionKey) LogKeyURLPath = string(semconv.URLPathKey) LogKeyURLQuery = string(semconv.URLQueryKey) LogKeyUserAgent = string(semconv.UserAgentOriginalKey) LogKeyStatusCode = string(semconv.HTTPResponseStatusCodeKey) )
Access log keys written by LogHandler, follow OTel semconv attribute names. ref: https://opentelemetry.io/docs/specs/semconv/http/http-spans/#http-server
Variables ¶
This section is empty.
Functions ¶
func CORS ¶
func CORS(opts ...CORSOption) func(http.Handler) http.Handler
CORS provides Cross-Origin Resource Sharing middleware. Example:
import (
"net/http"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
r.HandleFunc("/users", UserEndpoint)
r.HandleFunc("/projects", ProjectEndpoint)
// Apply the CORS middleware to our top-level router, with the defaults.
http.ListenAndServe(":8000", handlers.CORS()(r))
}
func CanonicalHost ¶
CanonicalHost is HTTP middleware that re-directs requests to the canonical domain. It accepts a domain and a status code (e.g. 301 or 302) and re-directs clients to this domain. The existing request path is maintained.
Note: If the provided domain is considered invalid by url.Parse or otherwise returns an empty scheme or host, clients are not re-directed.
Example:
r := mux.NewRouter()
canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302)
r.HandleFunc("/route", YourHandler)
log.Fatal(http.ListenAndServe(":7000", canonical(r)))
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
h := midx.CanonicalHost("https://www.example.com", http.StatusFound)(
http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),
)
req := httptest.NewRequest(http.MethodGet, "http://example.com/path", nil)
req.Host = "example.com"
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Location"))
}
Output: 302 https://www.example.com/path
func DefaultCORS ¶
func DefaultCORS(opts ...CORSOption) func(http.Handler) http.Handler
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
h := midx.DefaultCORS()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "/api", nil)
req.Header.Set("Origin", "https://app.example")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code)
fmt.Println(rec.Header().Get("Access-Control-Allow-Origin"))
}
Output: 200 *
func DefaultCompress ¶
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
body := []byte("hello world")
h := midx.DefaultCompress()(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write(body)
}))
req := httptest.NewRequest(http.MethodGet, "/", nil)
req.Header.Set("Accept-Encoding", "gzip")
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Header().Get("Content-Encoding"))
}
Output: gzip
func ExtractRouteAttrs ¶
func InjectContext ¶
func InjectContext(carriers ...contextx.Carrier) httpx.Middleware
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/x/contextx"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
c := contextx.NewT[int]()
h := midx.InjectContext(c.Carry(7))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
v, _ := c.From(r.Context())
fmt.Println(v)
}))
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
}
Output: 7
func LogHandler ¶
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/x/logx"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
ctx := logx.With(context.Background(), logx.Discard())
h := midx.LogHandler(true)(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
req := httptest.NewRequest(http.MethodGet, "/ok", nil).WithContext(ctx)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code)
}
Output: 200
func MetricHandler ¶
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/prometheus/client_golang/prometheus"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
reg := prometheus.NewRegistry()
h := midx.MetricHandler(reg)(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
req := httptest.NewRequest(http.MethodGet, "/.sys/metrics", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code)
}
Output: 200
func PProfHandler ¶
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/xoctopus/httpx/pkg/midx"
)
func main() {
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
h := midx.PProfHandler(true)(next)
req := httptest.NewRequest(http.MethodGet, "/.sys/debug/pprof/", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
fmt.Println(rec.Code)
}
Output: 200
Types ¶
type CORSOption ¶
type CORSOption func(*corshandler.Cors) error
CORSOption represents a functional option for configuring the CORS middleware.
func AllowCredentials ¶
func AllowCredentials() CORSOption
AllowCredentials can be used to specify that the user agent may pass authentication details along with the request.
func AllowedHeaders ¶
func AllowedHeaders(headers []string) CORSOption
AllowedHeaders adds the provided headers to the list of allowed headers in a CORS request. This is an append operation so the headers Accept, Accept-Language, and Content-Language are always allowed. Content-Type must be explicitly declared if accepting Content-Types other than application/x-www-form-urlencoded, multipart/form-data, or text/plain.
func AllowedMethods ¶
func AllowedMethods(methods []string) CORSOption
AllowedMethods can be used to explicitly allow methods in the Access-Control-Allow-Methods header. This is a replacement operation so you must also pass GET, HEAD, and POST if you wish to support those methods.
func AllowedOriginValidator ¶
func AllowedOriginValidator(fn OriginValidator) CORSOption
AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the 'Allow-Access-Control-Origin' HTTP header.
func AllowedOrigins ¶
func AllowedOrigins(origins []string) CORSOption
AllowedOrigins sets the allowed origins for CORS requests, as used in the 'Allow-Access-Control-Origin' HTTP header. Note: Passing in a []string{"*"} will allow any domain.
func ExposedHeaders ¶
func ExposedHeaders(headers []string) CORSOption
ExposedHeaders can be used to specify headers that are available and will not be stripped out by the user-agent.
func IgnoreOptions ¶
func IgnoreOptions() CORSOption
IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, instead passing them through to the next handler. This is useful when your application or framework has a pre-existing mechanism for responding to OPTIONS requests.
func MaxAge ¶
func MaxAge(age int) CORSOption
MaxAge determines the maximum age (in seconds) between preflight requests. A maximum of 10 minutes is allowed. An age above this value will default to 10 minutes.
func OptionStatusCode ¶
func OptionStatusCode(code int) CORSOption
OptionStatusCode sets a custom status code on the OPTIONS requests. Default behavior sets it to 200 to reflect best practices. This is option is not mandatory and can be used if you need a custom status code (i.e. 204).
More information on the spec: https://fetch.spec.whatwg.org/#cors-preflight-fetch
type OriginValidator ¶
type OriginValidator = corshandler.OriginValidator