router

package
v0.0.0-...-87e0fb7 Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2019 License: GPL-3.0 Imports: 1 Imported by: 0

Documentation

Overview

Package router provides utils to add middleware handlers to http handler functions.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Middleware

type Middleware func(http.HandlerFunc) http.HandlerFunc

type Router

type Router map[string]handler
Example
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"time"

	"github.com/trencat/netutils/http/router"
)

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Test handler\n")
}

func middleware(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Middleware acting before handler")

		fn(w, r)

		fmt.Fprint(w, "Middleware acting after handler")
	}
}

func funnyMiddleware(fn http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "FunnyMiddleware acting before handler")

		fn(w, r)

		fmt.Fprint(w, "FunnyMiddleware acting after handler")
	}
}

func main() {
	r := make(router.Router)

	// Request with no middleware
	r.HandlerFunc("/nomiddleware", handler)

	// Request with middleware
	r.AddRoute("/middleware", middleware)
	r.AddRoute("/middleware", funnyMiddleware)
	r.HandlerFunc("/middleware", handler)

	r.Build()

	// Run server, omitting error handling for clarity
	go http.ListenAndServe(":8080", nil)

	// Wait a second until server is up
	time.Sleep(time.Duration(1) * time.Second)

	// Do request. Omitting error handling for clarity
	response, _ := http.Get("http://127.0.0.1:8080/nomiddleware")
	body, _ := ioutil.ReadAll(response.Body)
	fmt.Printf("%s", body)

	// Do request. Omitting error handling for clarity
	response, _ = http.Get("http://127.0.0.1:8080/middleware")
	body, _ = ioutil.ReadAll(response.Body)
	fmt.Printf("%s", body)
}
Output:

func (*Router) Add

func (r *Router) Add(mw ...Middleware)

Add middleware handlers to all routes. See AddRoute for more details.

func (*Router) AddRoute

func (r *Router) AddRoute(route string, mw ...Middleware)

AddRoute adds middleware handlers to the given route. Middleware will executed in the order provided.

func (*Router) Build

func (r *Router) Build()

Build registers all middleware and http handlers set until now. This method must be called when all middleware and http handlers have been added.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(route string, h http.HandlerFunc)

HandlerFunc sets the handler function to the given route. There can be only one handler function per route.

Jump to

Keyboard shortcuts

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