midx

package
v1.0.0-rc2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 25 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

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

Examples

Constants

View Source
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

func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler

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 Compress

func Compress(level int) func(h http.Handler) http.Handler

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

func DefaultCompress() func(h http.Handler) http.Handler
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 DefaultLogHandler

func DefaultLogHandler() func(http.Handler) http.Handler

func ExtractBasicAttrs

func ExtractBasicAttrs(req *http.Request) []attribute.KeyValue

func ExtractRouteAttrs

func ExtractRouteAttrs(status int, info *types.OperationMeta, req *http.Request) []attribute.KeyValue

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

func LogHandler(enableOTel bool) func(http.Handler) http.Handler
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

func MetricHandler(gatherer prometheus.Gatherer) func(http.Handler) http.Handler
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

func PProfHandler(enabled bool) func(handler http.Handler) http.Handler
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

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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