middleware

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2020 License: MIT Imports: 9 Imported by: 0

README

Middlewares

  • Cyclops supports middlewares and few middlewares come pre-included with the project and they are:

    • CORS
    • Panic Handler
    • Request Logger
    • Set Secure Headers with every request
    • Set Default Headers with every request
  • Out of the above middlewares, PanicHandler and RequestLogger are enabled by default

  • You can also add your own custom middlewares, the only thing to take care of when writing custom middlewares is that the function should take in http.Handler as a parameter and return http.Handler

Using CORS Middleware

Cyclops supports CORS and can be used as explained below

package main

import (
	"fmt"
	"github.com/flannel-dev-lab/cyclops"
	"github.com/flannel-dev-lab/cyclops/middleware"
	"github.com/flannel-dev-lab/cyclops/router"
	"html/template"
	"net/http"
	"time"
)

func main() {

    cors := middleware.CORS{
    		AllowedOrigin: "https://www.admin.yombu.com",
    		AllowedHeaders: []string{"Content-Type", "referrer", "referrer-type"},
    		AllowedMethods: []string{"GET", "POST"},
    		AllowedCredentials: true,
    		ExposedHeaders: []string{"GET"},
    		MaxAge: 100,
    	}

	routerObj := router.New()
	routerObj.Get("/", middleware.NewChain(cors.CORSHandler).Then(Login))

	cyclops.StartServer(":8080", routerObj)
}

func Login(w http.ResponseWriter, r *http.Request) {
	response.SuccessResponse(200, w, nil)
}

Setting Default Headers with every request
package main

import (
	"fmt"
	"github.com/flannel-dev-lab/cyclops"
	"github.com/flannel-dev-lab/cyclops/middleware"
	"github.com/flannel-dev-lab/cyclops/response"
	"github.com/flannel-dev-lab/cyclops/router"
	"net/http"
)

func main() {

	~~defaultHeaders := middleware.DefaultHeaders{
        ContentType: "application/json",
	}~~

    routerObj := router.New()
    routerObj.Get("/", middleware.NewChain(DefaultHeaders.DefaultHeaders).Then(Login))
    
    cyclops.StartServer(":8080", routerObj)
}

func Login(w http.ResponseWriter, r *http.Request) {
	response.SuccessResponse(200, w, nil)
}

When we run the above code, the response header Content-Type: application/json is set with every request

Middleware Chaining

If you want to use multiple middlewares for a request, cyclops allows you to do that as well. All you need to do is like below:

middleware.NewChain(defaultHeaders.DefaultHeaders, cors.CORSHandler).Then(http.HandlerFunc(Login))

Documentation

Overview

middleware package includes different middleware available by default with cyclops, cyclops is made in such a way that it is easy for developers to plug custom middleware as well, the only thing that the developer need to do is write a middleware that takes in a http.Handler and returns a http.Handler, once the middleware is complete pass it to NewChain method to start using it

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func PanicHandler

func PanicHandler(h http.HandlerFunc) http.HandlerFunc

PanicHandler takes care of recovering from panic if any unforseen error occurs in the execution logic and makes sure that the server does not stop

func RequestLogger

func RequestLogger(h http.HandlerFunc) http.HandlerFunc

RequestLogger intercepts logs from the requests and prints them to stdout

Types

type CORS added in v0.1.0

type CORS struct {
	// AllowedOrigin Specifies which origin should be allowed, if you want to allow all use *
	AllowedOrigin string

	// AllowedCredentials indicates whether the response to the request can be exposed when the credentials flag is true.
	// The only valid value for this header is true (case-sensitive). If you don't need credentials,
	// omit this header entirely (rather than setting its value to false).
	AllowedCredentials bool

	// AllowedHeaders is used in response to a pre-flight request which includes the Access-Control-Request-Headers
	// to indicate which HTTP headers can be used during the actual request.
	AllowedHeaders []string

	// AllowedMethods is a list of methods the client is allowed to use with
	// cross-domain requests. Default value is simple methods (HEAD, GET and POST).
	AllowedMethods []string

	// ExposedHeaders indicates which headers can be exposed as part of the response by listing their names.
	ExposedHeaders []string

	// MaxAge indicates how long the results of a pre-flight request (that is the information contained in the
	// Access-Control-Allow-Methods and Access-Control-Allow-Headers headers) can be cached.
	// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
	MaxAge int
}

Contains all the CORS configurations

func (CORS) CORSHandler added in v0.1.0

func (cors CORS) CORSHandler(h http.HandlerFunc) http.HandlerFunc

CORSHandler handles the simple and pre-flight requests

type Chain

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

Chain contains a slice of middleware for the request

func NewChain

func NewChain(middlewares ...Middlewares) *Chain

NewChain takes a variable number of middleware's and adds them to chain and returns a pointer to Chain

func (*Chain) Then

func (chain *Chain) Then(handler http.HandlerFunc) http.HandlerFunc

Then will take in your handler that need to be executed with the requested path and chains all the middleware's that are specified in Chain, the note here is that middleware's are chained in the order they are specified, so take care of adding middleware's in appropriate order

type DefaultHeaders added in v0.1.0

type DefaultHeaders struct {
	// CacheControl general-header field is used to specify directives for caching mechanisms in both requests
	// and responses.
	CacheControl string
	// ContentLanguage entity header is used to describe the language(s) intended for the audience, so that it allows a user to
	// differentiate according to the users' own preferred language. Default is en-US
	ContentLanguage []string
	// ContentType entity header is used to indicate the media type of the resource.
	ContentType string
	// Expires header contains the date/time after which the response is considered stale.
	Expires string
	// LastModified response HTTP header contains the date and time at which the origin server believes the resource was last
	// modified. It is used as a validator to determine if a resource received or stored is the same.
	// Format: <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
	LastModified string
}

DefaultHeaders lets you manage a set of default headers as per mozilla spec https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers

func (*DefaultHeaders) SetDefaultHeaders added in v0.1.0

func (defaultHeaders *DefaultHeaders) SetDefaultHeaders(h http.HandlerFunc) http.HandlerFunc

SetDefaultHeaders will set certain default headers specified by the user

type LogObject added in v0.0.5

type LogObject struct {
	// Current timestamp of request
	Timestamp string `json:"timestamp"`
	// RemoteAddress contains the IP of the server/ the IP address of the proxy
	RemoteAddress string `json:"remote_address"`
	// TrueIP contains the IP of the original requester
	TrueIP string `json:"true_ip"`
	// Method contains the http method requested
	Method string `json:"method"`
	// Path contains the http path requested
	Path string `json:"path"`
	// Host contains the IP of host
	Host string `json:"host"`
	// Protocol contains http version
	Protocol string `json:"protocol"`
	// UserAgent
	UserAgent string `json:"user_agent"`
}

LogObject contains keys for the logs

type Middlewares

type Middlewares func(http.HandlerFunc) http.HandlerFunc

A type signature for middleware type Middlewares func(http.Handler) http.Handler

type SecureHeaders added in v0.1.2

type SecureHeaders struct {
	// Sets the X-XSS-Protection Header. Valid values are https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
	// Default is 1; mode=block
	XSSProtection string
	// ContentTypeOptions provides protection against overriding Content-Type
	// header by setting the `X-Content-Type-Options` header.
	// Optional. Default value "nosniff".
	ContentTypeOptions string
	// Sets X-Frame-Options header that can be used to indicate whether or not a browser should be allowed to render a
	// page in a <frame>, <iframe>, <embed> or <object>. Valid values are deny, sameorigin and allow-from uri. Default
	// is deny
	FrameOptions string

	// ReferrerPolicy sets the `Referrer-Policy` header providing security against
	// leaking potentially sensitive request paths to third parties.
	// Optional. Default value "".  https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
	ReferrerPolicy string
}

func (SecureHeaders) SetSecureHeaders added in v0.1.2

func (secureHeaders SecureHeaders) SetSecureHeaders(h http.HandlerFunc) http.HandlerFunc

SetSecureHeaders sets some default security headers

Jump to

Keyboard shortcuts

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