87 lines
1.9 KiB
Markdown
87 lines
1.9 KiB
Markdown
# chizap [![Build Status](https://woodpecker.dwysokinski.me/api/badges/4/status.svg)](https://woodpecker.dwysokinski.me/repos/4)
|
|
|
|
A request logging middleware for [go-chi](https://github.com/go-chi/chi) using [zap](https://github.com/uber-go/zap).
|
|
|
|
## Getting started
|
|
|
|
### Installation
|
|
|
|
```shell
|
|
go get gitea.dwysokinski.me/Kichiyaki/chizap
|
|
```
|
|
|
|
### Usage
|
|
|
|
```go
|
|
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"gitea.dwysokinski.me/Kichiyaki/chizap"
|
|
"github.com/go-chi/chi/v5"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
func main() {
|
|
logger, err := zap.NewDevelopment()
|
|
if err != nil {
|
|
log.Fatalln("zap.NewDevelopment", err)
|
|
}
|
|
|
|
http.ListenAndServe(":8080", newRouter(logger))
|
|
}
|
|
|
|
func newRouter(logger *zap.Logger) *chi.Mux {
|
|
router := chi.NewRouter()
|
|
|
|
router.Route("/", func(r chi.Router) {
|
|
r.Use(chizap.Logger(
|
|
logger,
|
|
chizap.WithFilter(func(r *http.Request) bool {
|
|
return r.URL.Path != "/excluded"
|
|
}),
|
|
chizap.WithFilter(func(r *http.Request) bool {
|
|
return r.URL.Path != "/excluded2"
|
|
}),
|
|
chizap.WithAdditionalFieldExtractor(func(r *http.Request) []zap.Field {
|
|
if !strings.HasPrefix(r.URL.Path, "/delete") {
|
|
return nil
|
|
}
|
|
|
|
return []zap.Field{
|
|
zap.String("id", chi.URLParam(r, "id")),
|
|
}
|
|
}),
|
|
))
|
|
r.Get("/info", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
r.Get("/warn", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
})
|
|
r.Get("/error", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
})
|
|
r.Get("/excluded", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
r.Delete("/delete/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
})
|
|
})
|
|
|
|
return router
|
|
}
|
|
```
|
|
|
|
## License
|
|
|
|
Distributed under the MIT License. See ``LICENSE`` for more information.
|
|
|
|
## Contact
|
|
|
|
Dawid Wysokiński - [contact@dwysokinski.me](mailto:contact@dwysokinski.me)
|