router

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 11, 2020 License: MIT Imports: 8 Imported by: 1

README

go-router-simple

test PkgGoDev Go Report Card

go-router-simple is a simple HTTP request router for Go. This package is ported from Router::Simple which is a great module in Perl.

Motivation: Most request routing third-party modules in Go are implemented using the trie (radix) tree algorithm. Hence, they are fast but it hard to provide flexible URL parameters. (e.g. URL paths containing /)

⚠️ Supports Go1.12 and above.

Synopsis

package main

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

	"github.com/Code-Hex/go-router-simple"
)

func main() {
	r := router.New()

	r.GET("/", http.HandlerFunc(Index))
	r.GET("/hi/:name", http.HandlerFunc(Hi))
	r.GET("/hi/{name}", http.HandlerFunc(Hi))
	r.GET("/download/*.*", http.HandlerFunc(GetFilename))
	r.GET(`/blog/{year:\d{4}}/{month:(?:\d{2})}`, Blog())

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

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

func Hi(w http.ResponseWriter, r *http.Request) {
	name := router.ParamFromContext(r.Context(), "name")
	fmt.Fprintf(w, "Welcome! %q\n", name)
}

func GetFilename(w http.ResponseWriter, r *http.Request) {
	wildcards := router.WildcardsFromContext(r.Context())
	fmt.Fprintf(w, "File: %q\n", strings.Join(wildcards, "."))
}

func Blog() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		year := router.ParamFromContext(r.Context(), "year")
		month := router.ParamFromContext(r.Context(), "month")
		fmt.Fprintf(w, "Render: %q\n", year+"/"+month)
	})
}

Advanced usage

go-router-simple is used regular expressions for traversal but it's a little slow. So you would better to use other third-party routing packages for traversing most request paths whenever possible.

Here's example. Basically, use httprouter, but use go-router-simple for complex URL parameters.

package main

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

	"github.com/Code-Hex/go-router-simple"
	"github.com/julienschmidt/httprouter"
)

func main() {
    // Setup go-router-simple.
	r := router.New()
	r.GET(`/blog/{year:(?:199\d|20\d{2})}/{month:(?:0?[1-9]|1[0-2])}`, Blog())

	// Setup httprouter.
	hr := httprouter.New()
	hr.GET("/hi/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		name := ps.ByName("name")
		fmt.Fprintf(w, "Welcome! %q\n", name)
	})
	hr.GET("/bye/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		name := ps.ByName("name")
		fmt.Fprintf(w, "Bye! %q\n", name)
	})

	// If not found on httprouter, it will traverse on go-router-simple.
	hr.NotFound = r

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

func Blog() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		year := router.ParamFromContext(r.Context(), "year")
		month := router.ParamFromContext(r.Context(), "month")
		fmt.Fprintf(w, "Render: %q\n", year+"/"+month)
	})
}
Result
$ curl localhost:8080/hi/codehex
Welcome! "codehex"
$ curl localhost:8080/bye/codehex
Bye! "codehex"
$ curl localhost:8080/blog/2020/11
Render: "2020/11"

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParamFromContext

func ParamFromContext(ctx context.Context, key string) string

ParamFromContext gets URL parameters from reqeust context.Context.

func WildcardsFromContext

func WildcardsFromContext(ctx context.Context) []string

WildcardsFromContext gets URL wildcard parameters from reqeust context.Context.

Types

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger interface represents error logger.

This package needs to log error on ServeHTTP. So this interface is used for that.

type Router

type Router struct {
	// ErrorLog logs error in ServeHTTP. If not specified, it defaults
	// to log.Printf is used.
	ErrorLog Logger

	// NotFound is configurable http.Handler which is called when no matching
	// route is found. If it is not set, http.NotFound is used.
	NotFound http.Handler
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func New

func New() *Router

New creates new Router struct.

func (*Router) CONNECT

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

CONNECT is a shorthand for router.Handle(http.MethodConnect, path, handle)

func (*Router) DELETE

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

DELETE is a shorthand for router.Handle(http.MethodDelete, path, handle)

func (*Router) GET

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

GET is a shorthand for router.Handle(http.MethodGet, path, handle)

func (*Router) HEAD

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

HEAD is a shorthand for router.Handle(http.MethodHead, path, handle)

func (*Router) Handle

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

Handle handles handler

func (*Router) HandleFunc

func (r *Router) HandleFunc(method, path string, handler func(http.ResponseWriter, *http.Request))

HandleFunc handles http.HandlerFunc

func (*Router) OPTIONS

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

OPTIONS is a shorthand for router.Handle(http.MethodOptions, path, handle)

func (*Router) PATCH

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

PATCH is a shorthand for router.Handle(http.MethodPatch, path, handle)

func (*Router) POST

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

POST is a shorthand for router.Handle(http.MethodPost, path, handle)

func (*Router) PUT

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

PUT is a shorthand for router.Handle(http.MethodPut, path, handle)

func (*Router) ServeHTTP

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

func (*Router) TRACE

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

TRACE is a shorthand for router.Handle(http.MethodTrace, path, handle)

Directories

Path Synopsis
example module

Jump to

Keyboard shortcuts

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