middleware

package
v0.0.0-...-760e1c2 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2019 License: MIT Imports: 10 Imported by: 0

README

middleware

The package middleware implements various middleware handler for httprouter. The package contains error, cors, log and authentication handlers.

package main

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

	"github.com/ricoberger/gocommon/middleware"

	"github.com/julienschmidt/httprouter"
)

func getUsers(w http.ResponseWriter, r *http.Request, _ httprouter.Params) *middleware.Error {
	user, err := db.GetUsers()
	if err != nil {
		return middleware.Errorf(err, http.StatusInternalServerError, "Internal Server Error")
	}

	return middleware.WriteJSON(w, r, nil)
}

func main() {
	var router = httprouter.New()
	router.GET("/users", middleware.Log(middleware.Handle(getUsers)))

	log.Fatalln(http.ListenAndServe(":8080", router))
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BasicAuth

func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle

BasicAuth handles basic authentication. It checkes if the the sent basic auth crendentials matchs the required user and password.

func BearerAuth

func BearerAuth(h httprouter.Handle, signingSecret string) httprouter.Handle

BearerAuth handles bearer token authentication. The claims from the JWT token can be accessed in the handler function as follows:

claims, ok := r.Context()
  .Value(middleware.ContextJWTKey)
  .(middleware.MapClaims)

func Cors

Cors sets cors headers.

func HandleError

func HandleError(h Handler) httprouter.Handle

HandleError display the error message to the user with the correct HTTP status code and log the full error to the developer console.

func Log

Log handles logging for http requests.

Types

type ContextKey

type ContextKey string

ContextKey implements type for context key.

const ContextJWTKey ContextKey = "jwt"

ContextJWTKey is the key for the jwt context value.

type Error

type Error struct {
	Error   error  `json:"-"`
	Message string `json:"message"`
	Code    int    `json:"code"`
}

Error is our custom error type. See: http://blog.golang.org/error-handling-and-go

func Errorf

func Errorf(err error, code int, format string, v ...interface{}) *Error

Errorf is our custom error function.

func Write

func Write(w http.ResponseWriter, r *http.Request, data interface{}) *Error

Write return json data.

type Handler

Handler is our custom HTTP handler. See: http://blog.golang.org/error-handling-and-go

Jump to

Keyboard shortcuts

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