Skip to content

Commit

Permalink
yaag httprouter middleware and update readme (#51)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesnaW authored Jul 21, 2022
1 parent 47d7814 commit 6c36126
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
22 changes: 22 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,28 @@ func main() {
}
```

## How to use with httprouter package

1. Import github.com/betacraft/yaag/yaag
2. Import github.com/betacraft/yaag/httprouteryaag
3. Initialize yaag ```yaag.Init(&yaag.Config{On: true, DocTitle: "Httprouter", DocPath: "apidoc.html"})```
4. Use it in your handlers as ```router.Handle("GET", "/", httprouteryaag.HandleFunc(handler))```

#### Sample code

```go
func handler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
yaag.Init(&yaag.Config{On: true, DocTitle: "Httprouter", DocPath: "apidoc.html", BaseUrls : map[string]string{"Production":"","Staging":""} })
router := httprouter.New()
router.Handle("GET", "/", httprouteryaag.HandleFunc(handler))
http.ListenAndServe(":8080", router)
}
```

## Screenshots

#### API doc is generated based on the paths
Expand Down
25 changes: 25 additions & 0 deletions httprouteryaag/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package httprouteryaag

import (
"net/http"

"github.com/betacraft/yaag/middleware"
"github.com/betacraft/yaag/yaag"
"github.com/betacraft/yaag/yaag/models"

"github.com/julienschmidt/httprouter"
)

func HandleFunc(next func(http.ResponseWriter, *http.Request, httprouter.Params)) httprouter.Handle {
return httprouter.Handle(func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if !yaag.IsOn() {
next(w, r, ps)
return
}
apiCall := models.ApiCall{}
writer := middleware.NewResponseRecorder(w)
middleware.Before(&apiCall, r)
next(writer, r, ps)
middleware.After(&apiCall, writer, r)
})
}

0 comments on commit 6c36126

Please sign in to comment.