httpwrapper

package module
v0.0.0-...-5ae9fe3 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2015 License: MIT Imports: 5 Imported by: 0

README

httpwrapper

httpwrapper is tiny library written in Golang for serving http requests and dealing with middlewares more easier.

Installing

go get github.com/minhduccm/httpwrapper

Example

package main

import (
	"net/http"

	"github.com/minhduccm/httpwrapper"
)

func TestHandlerFunc(res http.ResponseWriter, req *http.Request) (int, error) {
	res.Write([]byte("pong 123"))
	return 200, nil
}

func BarHandlerFunc(res http.ResponseWriter, req *http.Request) (int, error) {
	res.Write([]byte("bar"))
	return 200, nil
}

func AuthFunc(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {

		queryValues := r.URL.Query()
		key := queryValues.Get("key")
		if key != "minhduccm" {
			http.Error(w, http.StatusText(401), 401)
			return
		}
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func CustomFunc(key string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {

			queryValues := r.URL.Query()
			querykey := queryValues.Get("key")
			if querykey != key {
				http.Error(w, http.StatusText(401), 401)
				return
			}
			next.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
}

func main() {
	router := httpwrapper.NewRouter()

	router.Get("/ping", httpwrapper.Perform(httpwrapper.LoggingHandler, httpwrapper.RecoveryHandler, AuthFunc, CustomFunc("minhduccm")).LeadTo(TestHandlerFunc))

	router.Get("/foo", httpwrapper.Perform().LeadTo(BarHandlerFunc))

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

More detail, see docs:

http://godoc.org/github.com/minhduccm/httpwrapper

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func LoggingHandler

func LoggingHandler(next http.Handler) http.Handler

func Perform

func Perform(middlewares ...func(http.Handler) http.Handler) middlewares

func RecoveryHandler

func RecoveryHandler(next http.Handler) http.Handler

Types

type Router

type Router struct {
	*httprouter.Router
}

func NewRouter

func NewRouter() *Router

func (*Router) Delete

func (r *Router) Delete(path string, handler http.Handler)

func (*Router) Get

func (r *Router) Get(path string, handler http.Handler)

func (*Router) Head

func (r *Router) Head(path string, handler http.Handler)

func (*Router) Options

func (r *Router) Options(path string, handler http.Handler)

func (*Router) Patch

func (r *Router) Patch(path string, handler http.Handler)

func (*Router) Post

func (r *Router) Post(path string, handler http.Handler)

func (*Router) Put

func (r *Router) Put(path string, handler http.Handler)

Jump to

Keyboard shortcuts

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