The package provides a builder to build the http route matcher github.com/xgfone/go-apiserver/http/matcher.Matcher.
Install
$ go get -u github.com/xgfone/go-apiserver-httproute-matcher-ruler
Example
package main
import (
"fmt"
"net/http"
"github.com/xgfone/go-apiserver-httproute-matcher-ruler/ruler"
"github.com/xgfone/go-apiserver/http/reqresp"
"github.com/xgfone/go-apiserver/http/router"
)
func main() {
router := router.NewRouter()
router.BuildMatcherRule = ruler.Build // Set the builder of the matcher rule
// Route 1
router.
Rule("Method(`GET`) && Path(`/path1/{id}`)"). // Build the matcher
HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Set the handler
c := reqresp.GetContext(r)
fmt.Fprintf(w, "route1: %s", c.Datas["id"])
})
// Route 2
router.
Rule("Method(`GET`) && Path(`/path2/{id}`)"). // Build the matcher
HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Set the handler
c := reqresp.GetContext(r)
fmt.Fprintf(w, "route2: %s", c.Datas["id"])
})
http.ListenAndServe("127.0.0.1:80", router)
// Open a terminal and run the program:
// $ go run main.go
//
// Open another terminal and run the http client:
// $ curl http://127.0.0.1/path1/123
// route1: 123
// $ curl http://127.0.0.1/path2/123
// route2: 123
}