diff --git a/example/main.go b/example/main.go new file mode 100644 index 0000000..0722841 --- /dev/null +++ b/example/main.go @@ -0,0 +1,55 @@ +package main + +import ( + "encoding/json" + "github.com/icbd/go_restful_routes" + "github.com/icbd/go_restful_routes/static" + "net/http" + "os" + "time" +) + +func main() { + if err := http.ListenAndServe(":3000", Handler()); err != nil { + panic(err) + } +} + +func Handler() http.Handler { + r := go_restful_routes.NewRoutingTable() + r.Get("/hi", HiController) + r.Post("/users/{int:Uid}", ShowUser) + r.Any("/", RootController) + return r +} + +type user struct { + Uid int `json:"uid"` + CreatedAt time.Time `json:"created_at"` +} + +// GET /hi +func HiController(w http.ResponseWriter, req *http.Request) { + _, _ = w.Write([]byte("

hi

")) +} + +// GET /users/123 +func ShowUser(w http.ResponseWriter, req *http.Request) { + params := go_restful_routes.Params(req) + u := user{Uid: params["Uid"].(int), CreatedAt: time.Now()} + if data, err := json.Marshal(u); err == nil { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write(data) + } +} + +// ANY / +// ANY /404.html +// ANY /avatar.png +func RootController(w http.ResponseWriter, req *http.Request) { + if req.URL.Path != "/" { + static.New(w, req, os.Getenv("PUBLIC_DIR"), "/", "png", "html") + return + } + _, _ = w.Write([]byte("

Welcome~

")) +} diff --git a/example/public/404.html b/example/public/404.html new file mode 100644 index 0000000..bb5559c --- /dev/null +++ b/example/public/404.html @@ -0,0 +1,10 @@ + + + + + 404 + + +

404 static page

+ + \ No newline at end of file diff --git a/example/public/favicon.ico b/example/public/favicon.ico new file mode 100644 index 0000000..ee1e62a Binary files /dev/null and b/example/public/favicon.ico differ diff --git a/match.go b/match.go index d725068..794c7f6 100644 --- a/match.go +++ b/match.go @@ -8,6 +8,9 @@ import ( type pathParams map[string]interface{} func newPathParams(patternBlocks []string, pathBlocks []string) (pathParams, bool) { + if len(patternBlocks) != len(pathBlocks) { + return nil, false + } params := make(pathParams) for i, patternBlock := range patternBlocks { if ok := params.match(patternBlock, pathBlocks[i]); !ok { diff --git a/readme.md b/readme.md index dfe144e..3fbc895 100644 --- a/readme.md +++ b/readme.md @@ -10,6 +10,13 @@ ```shell script go get github.com/icbd/go_restful_routes ``` + +## Run Example + +```shell script +$ PUBLIC_DIR=example/public go run example/main.go +``` + ## How to use Initialize a new routing table using `NewRoutingTable`. @@ -74,6 +81,7 @@ go_restful_routes.Log = func(s string) { } } ``` + ## License MIT, see [LICENSE](LICENSE)