go-apiserver-httproute-matcher-ruler

module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2022 License: Apache-2.0

README

Go APIServer HTTP Route Metcher Ruler Build Status GoDoc License

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
}

Directories

Path Synopsis
Package ruler provides the matcher rule parser and builder.
Package ruler provides the matcher rule parser and builder.

Jump to

Keyboard shortcuts

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