middleware

package module
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2025 License: MIT Imports: 1 Imported by: 10

README

middlewares - HTTP Middleware Handler(s)

Provides an HTTP middleware for go HTTP servers.

Documentation

Official godoc documentation (with examples) can be found at the Package Registry.

Usage

Add Package Dependency
go get -u github.com/poly-gun/go-middleware
Import and Implement

main.go

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log/slog"
    "net"
    "net/http"
    "time"

    "github.com/poly-gun/go-middleware"
)

func main() {
    ctx := context.Background()
    mux := http.NewServeMux()
    server := &http.Server{
        Addr:           fmt.Sprintf("0.0.0.0:%s", "8080"),
        Handler:        mux,
        ReadTimeout:    15 * time.Second,
        WriteTimeout:   60 * time.Second,
        IdleTimeout:    30 * time.Second,
        MaxHeaderBytes: http.DefaultMaxHeaderBytes,
        BaseContext: func(net.Listener) context.Context {
            return ctx
        },
    }

    defer server.Shutdown(ctx)

    handle := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        var response = map[string]interface{}{
            "key-1": "value-1",
            "key-2": "value-2",
            "key-3": "value-3",
        }

        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusOK)
        json.NewEncoder(w).Encode(response)

        return
    })

    middleware := new(middlewares.Middleware)

    middleware.Add(func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()

            slog.InfoContext(ctx, "Middleware-1")

            ctx = context.WithValue(r.Context(), "Context-Key-1", "Context-Key-Value-1")

            next.ServeHTTP(w, r.WithContext(ctx))
        })
    })

    middleware.Add(func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            ctx := r.Context()

            slog.InfoContext(ctx, "Middleware-2")

            if v, ok := ctx.Value("Context-Key-1").(string); ok {
                w.Header().Set("X-Context-Key-1", v)
            }

            next.ServeHTTP(w, r.WithContext(ctx))
        })
    })

    mux.Handle("/", middleware.Handler(handle))

    if e := server.ListenAndServe(); e != nil {
        slog.ErrorContext(ctx, "Server Error", slog.Any("error", e))
    }

    return
}

Contributions

See the Contributing Guide for additional details on getting started.

Documentation

Overview

Package middlewares provides a collection of reusable HTTP middleware functionality to enable common tasks such as request logging, authentication, request validation, and other cross-cutting concerns in a web application.

Middleware in this package is typically designed to be used with an HTTP router or framework like net/http, providing a clean and efficient way to process HTTP requests and responses.

Example
mux := http.NewServeMux()

mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
	datum := map[string]interface{}{
		"key": "value",
	}

	defer json.NewEncoder(w).Encode(datum)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	return
})

middleware := middleware.New()

middleware.Add(func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		slog.InfoContext(ctx, "Middleware-1")

		ctx = context.WithValue(r.Context(), "Context-Key-1", "Context-Key-Value-1")

		next.ServeHTTP(w, r.WithContext(ctx))
	})
})

middleware.Add(func(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()

		slog.InfoContext(ctx, "Middleware-2")

		if v, ok := ctx.Value("Context-Key-1").(string); ok {
			w.Header().Set("X-Context-Key-1", v)
		}

		next.ServeHTTP(w, r.WithContext(ctx))
	})
})

server := httptest.NewServer(middleware.Handler(mux))

defer server.Close()

client := server.Client()
request, e := http.NewRequest(http.MethodGet, server.URL, nil)
if e != nil {
	e = fmt.Errorf("unexpected error while generating request: %w", e)

	panic(e)
}

response, e := client.Do(request)
if e != nil {
	e = fmt.Errorf("unexpected error while generating response: %w", e)

	panic(e)
}

defer response.Body.Close()

header := response.Header.Get("X-Context-Key-1")

fmt.Printf("X-Context-Key-1 Middleware Header: %s", header)
Output:

X-Context-Key-1 Middleware Header: Context-Key-Value-1

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Configurable

type Configurable[Options interface{}] interface {
	// Handler wraps the provided [http.Handler] with middleware functionality and returns a new [http.Handler].
	Handler(next http.Handler) http.Handler

	// Settings applies configuration functions to the middleware's options and returns the updated middleware.
	Settings(...func(o *Options)) Configurable[Options]
}

Configurable defines an interface for applying configurable behaviors to HTTP handlers using generic Options settings.

type Middleware

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

Middleware represents a structure to manage a chain of HTTP middleware functions. It wraps and applies middleware to an http.Handler in order of addition.

func New

func New() *Middleware

New initializes and returns a pointer to a new Middleware instance.

func (*Middleware) Add

func (m *Middleware) Add(middleware ...func(http.Handler) http.Handler)

Add appends one or more middleware functions to the middleware chain in the order they are provided.

func (*Middleware) Handler

func (m *Middleware) Handler(parent http.Handler) (handler http.Handler)

Handler applies the middleware chain to the provided parent http.Handler and returns the final wrapped handler. If no middleware is present, the parent handler is returned as is.

Directories

Path Synopsis
middleware
cors Module
envoy Module
name Module
rip Module
service Module
telemetrics Module
timeout Module
useragent Module
versioning Module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳