middleware

package
v0.0.93 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2024 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package middleware provides helpful functions that implement some common functionalities in http servers. A middleware is a function that takes in a http.Handler as one of its arguments and returns a http.Handler

The middlewares All, Get, Post, Head, Put & Delete wrap other internal middleware. The effect of this is that the aforementioned middleware, in addition to their specialised functionality, will:

  1. Add logID for traceability.
  2. Add the "real" client IP address to the request context.
  3. Add client TLS fingerprint to the request context.
  4. Recover from panics in the wrappedHandler.
  5. Log http requests and responses.
  6. Try and prevent path traversal attack.
  7. Rate limit requests by IP address.
  8. Shed load based on http response latencies.
  9. Handle automatic procurement/renewal of ACME tls certificates.
  10. Redirect http requests to https.
  11. Add some important HTTP security headers and assign them sensible default values.
  12. Implement Cross-Origin Resource Sharing support(CORS).
  13. Provide protection against Cross Site Request Forgeries(CSRF).
  14. Attempt to provide protection against form re-submission when a user reloads an already submitted web form.
  15. Implement http sessions.
Example (GetCspNonce)
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
)

func loginHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cspNonce := middleware.GetCspNonce(r.Context())
		_ = cspNonce

		_, _ = fmt.Fprint(w, "welcome to your favorite website.")
	}
}

func main() {
	l := log.New(context.Background(), os.Stdout, 100)
	handler := middleware.Get(
		loginHandler(),
		config.WithOpts("example.com", 443, "super-h@rd-Pas1word", config.DirectIpStrategy, l),
	)
	_ = handler // use handler

}
Output:

Example (GetCsrfToken)
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
)

func welcomeHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		csrfToken := middleware.GetCsrfToken(r.Context())
		_ = csrfToken

		_, _ = fmt.Fprint(w, "welcome.")
	}
}

func main() {
	l := log.New(context.Background(), os.Stdout, 100)
	handler := middleware.Get(
		welcomeHandler(),
		config.WithOpts("example.com", 443, "super-h@rd-Pas1word", config.DirectIpStrategy, l),
	)
	_ = handler // use handler

}
Output:

Index

Examples

Constants

View Source
const (
	// CsrfTokenFormName is the name of the html form name attribute for csrf token.
	CsrfTokenFormName = "csrftoken" // named after what django uses.
	// CsrfHeader is the name of the http header that Ong uses to store csrf token.
	CsrfHeader = "X-Csrf-Token" // named after what fiber uses.

)

Variables

This section is empty.

Functions

func All

func All(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

All is a middleware that allows all http methods.

See the package documentation for the additional functionality provided by this middleware.

Example
package main

import (
	"context"
	"io"
	"net/http"
	"os"

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
)

func main() {
	l := log.New(context.Background(), os.Stdout, 100)
	opts := config.WithOpts("example.com", 443, "super-h@rd-Pas1word", config.DirectIpStrategy, l)

	myHandler := http.HandlerFunc(
		func(w http.ResponseWriter, _ *http.Request) {
			_, _ = io.WriteString(w, "Hello from a HandleFunc \n")
		},
	)

	handler := middleware.All(myHandler, opts)

	mx := http.NewServeMux()
	mx.Handle("/", handler)

}
Output:

func BasicAuth

func BasicAuth(wrappedHandler http.Handler, user, passwd, hint string) http.HandlerFunc

BasicAuth is a middleware that protects wrappedHandler using basic authentication.

func ClientFingerPrint added in v0.0.44

func ClientFingerPrint(r *http.Request) string

ClientFingerPrint returns the TLS fingerprint of the client. It is provided on a best-effort basis. If a fingerprint is not found, it returns a string that has the substring "NotFound" in it. There are different formats/algorithms of fingerprinting, this library(by design) does not subscribe to a particular format or algorithm.

func ClientIP added in v0.0.26

func ClientIP(r *http.Request) string

ClientIP returns the "real" client IP address. This will be based on the [ClientIPstrategy] that you chose.

Warning: This should be used with caution. Clients CAN easily spoof IP addresses. Fetching the "real" client is done in a best-effort basis and can be grossly inaccurate & precarious. You should especially heed this warning if you intend to use the IP addresses for security related activities. Proceed at your own risk.

func Delete

func Delete(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

Delete is a middleware that only allows http DELETE requests and http OPTIONS requests.

See the package documentation for the additional functionality provided by this middleware.

func Get

func Get(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

Get is a middleware that only allows http GET requests and http OPTIONS requests.

See the package documentation for the additional functionality provided by this middleware.

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"os"

	"github.com/komuw/ong/config"
	"github.com/komuw/ong/log"
	"github.com/komuw/ong/middleware"
)

func loginHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cspNonce := middleware.GetCspNonce(r.Context())
		_ = cspNonce

		_, _ = fmt.Fprint(w, "welcome to your favorite website.")
	}
}

func main() {
	l := log.New(context.Background(), os.Stdout, 100)
	opts := config.WithOpts("example.com", 443, "super-h@rd-Pas1word", config.DirectIpStrategy, l)
	handler := middleware.Get(loginHandler(), opts)
	_ = handler // use handler

}
Output:

func GetCspNonce

func GetCspNonce(c context.Context) string

GetCspNonce returns the Content-Security-Policy nonce that was set for the http request in question.

func GetCsrfToken

func GetCsrfToken(c context.Context) string

GetCsrfToken returns the csrf token that was set for the http request in question.

func Head(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

Head is a middleware that only allows http HEAD requests and http OPTIONS requests.

See the package documentation for the additional functionality provided by this middleware.

func Post

func Post(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

Post is a middleware that only allows http POST requests and http OPTIONS requests.

See the package documentation for the additional functionality provided by this middleware.

func Put

func Put(wrappedHandler http.Handler, o config.Opts) http.HandlerFunc

Put is a middleware that only allows http PUT requests and http OPTIONS requests.

See the package documentation for the additional functionality provided by this middleware.

Types

This section is empty.

Jump to

Keyboard shortcuts

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