Skip to content

Commit

Permalink
Merge pull request #3 from icbd/example
Browse files Browse the repository at this point in the history
Example
  • Loading branch information
icbd authored Oct 6, 2020
2 parents e54a38c + 426b73f commit 9430e12
Show file tree
Hide file tree
Showing 5 changed files with 76 additions and 0 deletions.
55 changes: 55 additions & 0 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -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("<h1>hi</h1>"))
}

// 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("<h1>Welcome~</h1>"))
}
10 changes: 10 additions & 0 deletions example/public/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>404</title>
</head>
<body>
<h1>404 static page</h1>
</body>
</html>
Binary file added example/public/favicon.ico
Binary file not shown.
3 changes: 3 additions & 0 deletions match.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -74,6 +81,7 @@ go_restful_routes.Log = func(s string) {
}
}
```

## License

MIT, see [LICENSE](LICENSE)

0 comments on commit 9430e12

Please sign in to comment.