Categorygithub.com/sinnott74/go-http-middleware
modulepackage
0.0.0-20181110020803-6b384d713097
Repository: https://github.com/sinnott74/go-http-middleware.git
Documentation: pkg.go.dev

# README

go-http-middleware

Build Status

Collection of Golang HTTP middlewares fo use with Go's net/http package

  • etag Adds ETag support for each resource.

  • https Forces X-Forwarded-Proto header to be set to HTTPS. Useful when behind a load balancer i.e. aws, cloudfoundry, etc.

  • auth handles authenication using a user supplied authenication function.

  • JWT handles JWT authenication which allows a user supplied validation function.

  • Transaction creates a request scoped sql transation.

Installation

go get https://github.com/sinnott74/go-http-middleware

Example Usage

package main

import (
	"net/http"

	"github.com/sinnott74/go-http-middleware"
)

func main() {
	http.Handle("/", middleware.DefaultEtag(helloWorldHandler()))
	http.ListenAndServe(":8080", nil)
}

// Simple hello world handler
func helloWorldHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("Hello, World!"))
	})
}

// Visiting localhost:8080/ returns a response body of "Hello, world" and an ETag header 'W/"d-ZajifYh5KDgxtmS9i38K1A=="'

# Functions

Auth middleware is responsible handling request authentication The authentication is handled by the supplied AuthFunc.
DefaultEtag middleware which uses MD5 as its hashing function.
Etag middleware which handles adding an ETag header to the response An ETag is a hash of a resource that client's/browser use to cache resourse that are unchanged.
GetTransaction gets the transation stored in the context.
HTTPS middleware is responsible for redirecting the user to HTTPS It looks at the x-forward-proto header to determine the protocol used x-forward-proto is commonly set when behind load balancer which will terminate the ssl connection.
JWT is middleware which handles authentication for JsonWebTokens.
Transaction middleware starts a database transaction and adds it to the request context.

# Structs

JWTOptions defines the user supplied JWT configuration options.

# Type aliases

AuthFunc defines the user supplied function to implement Authorisation It is given the current request context and the Authorization header value and returns the context object to use with further chained http handlers.
JWTFunc defines a user supplied authorisation function.
Middleware is defined as a function which takes a http handler and returns a new http handler which wraps the input with extra functionality.
TokenExtractor is a function that takes the authorization header value as input and returns either a token or an error.