route

package module
v0.0.0-...-9a78f75 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2019 License: MIT Imports: 3 Imported by: 0

README

go-route - a regexp based router

go-route allows you to create multi level regexp-based routing for your application with registering named parameters in regexp.

Parameters from regexp routing are passed through request's context. You can fetch parameters using rotue.GetParams function, it accepts only one parameter which is request, and returns map[string]string. In returned map keys are named groups and values are matched values from URL.

Middlewares

Allowed methods

This middleware checks if request method is allowed.

Use consts from net/http for methos names, i.e. http.MethodPost.

package main

import (
    "net/http"

    "github.com/Alkemic/go-route/middleware"
)

middleware.AllowedMethods([]string{http.MethodPost, http.MethodPut}])(
    func(w http.ResponseWriter, r *http.Request) {
        p := route.GetParams(req)
        // actual code
    }
)
Panic interceptors

This middleware catches panics and logs them, and then returns 500 to the user. 500 handler can be overriden by

Differences between PanicInterceptor and PanicInterceptorWithLogger is that, the second one is parametrised decorator that accepts instance of *log.Logger. If first one is use, it uses standard log.Printf/log.Println.

package main

import (
    "log"
    "net/http"
    "os"

    "github.com/Alkemic/go-route/middleware"
)

middleware.PanicInterceptor(
    func(w http.ResponseWriter, r *http.Request) {
        p := route.GetParams(req)
        // actual code
    }
)
package main

import (
    "log"
    "net/http"
    "os"

    "github.com/Alkemic/go-route"
    "github.com/Alkemic/go-route/middleware"
)

var logger = log.New(os.Stdout, "", log.LstdFlags|log.Lshortfile)

middleware.PanicInterceptorWithLogger(logger)(
    func(w http.ResponseWriter, r *http.Request) {
        p := route.GetParams(req)
        // actual code
    }
)
Set headers

This middleware is used to set given headers to response.

package main

import (
    "net/http"

    "github.com/Alkemic/go-route"
    "github.com/Alkemic/go-route/middleware"
)

header := map[string]string{
    "Content-Type": "application/json",
}

middleware.SetHeaders(logger)(
    func(w http.ResponseWriter, r *http.Request) {
        p := route.GetParams(req)
        // actual code
    }
)
BasicAuthenticate

Setups HTP basic authenticate, for given view. Accepts functions that will verify credentials. Comes with two default functions that will do that:

  • Authenticate - accepts user and password
  • AuthenticateList - accept map (user => password)

Custom verification function must have following signature func(user string, password string) (string, error).

package main

import (
    "net/http"

    "github.com/Alkemic/go-route"
    "github.com/Alkemic/go-route/middleware"
)

authenticateFunc = middleware.Authenticate("username", "password")

middleware.BasicAuthenticate(logger, authenticateFunc, "realm name")(
    func(w http.ResponseWriter, r *http.Request) {
        user, err := middleware.GetUser(r)
    }
)
Noop

Does noting. Simply returns provided functions. Can be useful when used as default option in some cases.

Examples

Example function
package main

import (
    ...
    "github.com/Alkemic/go-route"
)

func News(w http.ResponseWriter, r *http.Request) {
    p := route.GetParams(req)
    pk, _ := strconv.Atoi(p["pk"])
    news, _ := model.GetNews(pk)
    comments, _ := news.GetComments()
    _ = json.NewEncoder(w).Encode(map[string]interface{}{
        "Entry":    news,
        "Comments": comments,
    })
}

Example routing definition
package main

import (
    ...
    "github.com/Alkemic/go-route"
)

func main() {
    newsRoutes := route.RegexpRouter{}
    newsRoutes.Add(`^$`, view.NewsList)
    newsRoutes.Add(`^(?P<pk>\d+)/$`, view.News)
    newsRoutes.Add(`^(?P<pk>\d+),(?P<slug>[a-z\-_]+)\.html$`, view.News)

    routing := route.RegexpRouter{}
    routing.Add(`^/news/`, newsRoutes)

    // register custom 404 handler function
    route.NotFound = helper.Handle404

    log.Fatalln(http.ListenAndServe("0.0.0.0:80", routing))
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	NotFound            = http.NotFound
	InternalServerError = func(w http.ResponseWriter, _ *http.Request) {
		http.Error(w, "500 internal server error", http.StatusInternalServerError)
	}
)

Functions

func GetParam

func GetParam(r *http.Request, key string) (string, bool)

GetParam returns single parsed parameter from url, along with indicator if it was success.

func GetParams

func GetParams(r *http.Request) map[string]string

GetParams returns map of parameters parsed from url, will be empty in case if there were no params.

func SetParam

func SetParam(r *http.Request, key, value string)

Types

type Handler

type Handler interface {
	ServeHTTP(http.ResponseWriter, *http.Request)
	// contains filtered or unexported methods
}

type HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request)

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

type RegexpRouter

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

RegexpRouter

func (*RegexpRouter) Add

func (h *RegexpRouter) Add(pattern string, handler interface{})

func (RegexpRouter) ServeHTTP

func (h RegexpRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)

Directories

Path Synopsis
_example

Jump to

Keyboard shortcuts

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