73
Routebuilder - #web #http #route
source link: https://www.tuicool.com/articles/iIfUFbz
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
routebuilder
This utility provide some methods to build your http routes fluently .
Single route
In the example section there is also a Middleware()
calls, those middleware are built at Build()
, in that way you can easily add middleware to your route.
Multi routes
If you need to build a lot of routes, with the same middleware under a specific path (e.g. /api/users
) the package also provide a routebuilder.Parent
builder.
Examples
Builder
package main import "net/http" // main func func GetUsers() *routebuilder.Route { return routebuilder.New(routebuilder.GET). Path("/api/v1/users"). Middleware(middleware.BasicAuth(myAuthFunc)). HandlerFunc( func(w http.ResponseWriter, r *http.Request) { // TODO: implement }, ). Build() }
Parent
package main // main func func UserRoutes() []*routebuilder.Route { return routebuilder.WithParent("/api/v1/users"). AddMiddlewares(someMiddlewares...). Get("", getUsersHandler). // /api/v1/users Post(":id", createUserHandler). // /api/v1/users/:id Routes() } func getUsersHandler() http.HandlerFunc { panic("not implemented yet") } func createUserHandler() http.HandlerFunc { panic("not implemented yet") }
Assembling with goji
Single
package main import ( "fmt" "net/http" "github.com/askm3/routebuilder" "goji.io" "goji.io/pat" ) func main() { mux := goji.NewMux() r := GetUsers() path := pat.NewWithMethods(r.GetPath(), r.GetMethod()) mux.HandleFunc(path, rb.GetHandler()) http.ListenAndServe("localhost:8000", mux) }
Multi
package main import ( "fmt" "net/http" "github.com/askm3/routebuilder" "goji.io" "goji.io/pat" ) func main() { mux := goji.NewMux() for _, r := range UserRoutes() { path := pat.NewWithMethods(r.GetPath(), r.GetMethod()) mux.HandleFunc(path, r.HandlerFunc()) } http.ListenAndServe("localhost:8000", mux) }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK