Skip to content
No description, website, or topics provided.
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
middleware
.gitignore
LICENSE
README.md
go.mod
parentBuilder.go
parentBuilder_test.go
routebuilder.go
routebuilder.png
routebuilder_test.go

README.md

routebuilder

routebuilder_gopher

This utility provides 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").
    Middleware(someMiddleware...).
    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)
}
You can’t perform that action at this time.