gomw

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2021 License: MIT Imports: 2 Imported by: 3

README

gomw - go-http-middleware

A framework for fasten creating Go HTTP Middleware

Get it

$ go get -u github.com/vchitai/gomw

Usage

Implement a simple authenticate middleware with gomw, find it at example

package main

import (
	"log"
	"net"
	"net/http"

	"github.com/vchitai/gomw"
)

const AccessToken = "something"

func isValidToken(token string) bool {
	if token == AccessToken {
		return true
	}
	return false
}

func main() {
	authenticateMw := gomw.NewHTTPMiddleware(func(writer http.ResponseWriter, request *http.Request) (*http.Request, bool) {
		token := request.Header.Get("Authorization")
		if isValidToken(token) {
			return request, true
		}

		writer.WriteHeader(http.StatusUnauthorized)
		_, _ = writer.Write([]byte(http.StatusText(http.StatusUnauthorized)))
		return nil, false
	}, func(resp gomw.HTTPResponse) gomw.HTTPResponse {
		return gomw.NewHTTPResponse(resp.Body(), resp.Code()) // do some edit
	})

	var mux = http.NewServeMux() // create new server
	mux.Handle("/", authenticateMw(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
		_, _ = writer.Write([]byte("Hello world!"))
	})))

	l, err := net.Listen("tcp", ":10080")
	if err != nil {
		log.Fatal(err)
	}

	if err := http.Serve(l, mux); err != nil {
		log.Fatal(err)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AfterHook

type AfterHook func(response HTTPResponse) HTTPResponse

type BeforeHook

type BeforeHook func(writer http.ResponseWriter, request *http.Request) (*http.Request, bool)

type HTTPMiddleware

type HTTPMiddleware func(next http.Handler) http.Handler

func NewHTTPAfterMiddleware

func NewHTTPAfterMiddleware(after AfterHook) HTTPMiddleware

func NewHTTPBeforeMiddleware

func NewHTTPBeforeMiddleware(before BeforeHook) HTTPMiddleware

func NewHTTPMiddleware

func NewHTTPMiddleware(before BeforeHook, after AfterHook) HTTPMiddleware

type HTTPResponse

type HTTPResponse interface {
	Body() []byte
	Code() int
}

func NewHTTPResponse

func NewHTTPResponse(body []byte, code int) HTTPResponse

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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