tinyrouter

package module
v0.0.0-...-20aa658 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2020 License: MIT Imports: 6 Imported by: 0

README

tinyrouter

Minimum HTTP request router

Usage

package main

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

	"github.com/FGtatsuro/tinyrouter"
)

func main() {
	router := tinyrouter.New()
	// Same signature to http.Handle
	router.Handle("/handle", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("handle\n"))
	}))
	// Same signature to http.HandleFunc
	router.HandleFunc("/handlefunc", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("handlefunc\n"))
	})
	// Get PathVars via context
	router.HandleFunc("/users/{[0-9a-zA-Z]+}", func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		vars := ctx.Value(tinyrouter.PathVarsContextKey).([]string)
		w.Write([]byte(fmt.Sprintf("user %v\n", vars[0])))
	})
	http.Handle("/", router)

	log.Fatal(http.ListenAndServe(":8080", nil))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	PathVarsContextKey = &contextKey{"path-match"}
)

Functions

This section is empty.

Types

type Router

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

func New

func New() *Router

func (*Router) Handle

func (router *Router) Handle(pattern string, handler http.Handler)

func (*Router) HandleFunc

func (router *Router) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

func (*Router) ServeHTTP

func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

Jump to

Keyboard shortcuts

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