Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GoHttpRouter

A http router utility for golang net/http library which can be used either as a mux or as a standalone router

Latest release

Usage

router := gohttprouter.NewRouter()

router.GET("/", handler) // handler should match signature - func (http.ResponseWriter, *http.Request) {}

router.POST("/save", saveHandler)

http.ListenAndServe(port, router)

Allowed Methods

GET, POST, PUT, PATCH, DELETE

Dynamic Routing

Dynamic route can be defined by prefixing a path value with a colon. For eg, router.GET("/view/:title") will allow all routing that matches /view/*. To fetch the dynamic value, *http.Request's PathValue method can be used

Example

import (
    "fmt"
    "net/http"
    "github.com/blackistheneworange/gohttprouter"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
    title := r.PathValue("title")

    fmt.Fprintf(w, "Page title: %s", title)
}

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

    router.GET("/view/:title", myHandler)

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

Middleware

Middleware handlers are allowed to be passed in any of the available methods in between the route path and http handler.

A middleware handler should match the following signature

func (http.ResponseWriter, *http.Request, gohttprouter.NextFunction) {}

Example

import (
    "fmt"
    "net/http"
    "github.com/blackistheneworange/gohttprouter"
)

func myHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello world!")
}

func customMiddleware(w http.ResponseWriter, r *http.Request, next gohttprouter.NextFunction) {
    // some actions
    next(w, r)
}

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

    router.GET("/", customMiddleware, myHandler)

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

About

A http router utility for golang net/http library which can be used either as a mux or as a standalone router

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages