Restructure all http related files
Moving all http related functions and helpers into a new http submodule
This commit is contained in:
parent
0a0c185c06
commit
18bf623114
4 changed files with 4 additions and 4 deletions
16
http/chain.go
Normal file
16
http/chain.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
)
|
||||
|
||||
type HandlerBuilder func(http.Handler) http.Handler
|
||||
|
||||
func ChainMiddlewares(base http.Handler, links ...HandlerBuilder) http.Handler {
|
||||
slices.Reverse(links)
|
||||
for _, f := range links {
|
||||
base = f(base)
|
||||
}
|
||||
return base
|
||||
}
|
19
http/context.go
Normal file
19
http/context.go
Normal file
|
@ -0,0 +1,19 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func ContextValsMiddleware(pairs map[any]any) HandlerBuilder {
|
||||
return func(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
for key, val := range pairs {
|
||||
ctx = context.WithValue(ctx, key, val)
|
||||
}
|
||||
newRequest := r.WithContext(ctx)
|
||||
h.ServeHTTP(w, newRequest)
|
||||
})
|
||||
}
|
||||
}
|
16
http/httpErr.go
Normal file
16
http/httpErr.go
Normal file
|
@ -0,0 +1,16 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// Return an error over an http connection.
|
||||
// The error will have the given return code `code`
|
||||
// and a json encoded body with the field "id" set to `errId`
|
||||
// and a field "message" set to the `message`
|
||||
func HttpErr(w http.ResponseWriter, errId int, message string, code int) {
|
||||
w.WriteHeader(code)
|
||||
w.Header().Add("Content-Type", "application/json")
|
||||
fmt.Fprintf(w, "{\"id\": %d, \"message\": \"%s\"}", errId, message)
|
||||
}
|
32
http/zerolog.go
Normal file
32
http/zerolog.go
Normal file
|
@ -0,0 +1,32 @@
|
|||
package http
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/hlog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
func LoggingMiddleware(handler http.Handler) http.Handler {
|
||||
return ChainMiddlewares(handler,
|
||||
hlog.NewHandler(log.Logger),
|
||||
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
|
||||
if strings.HasPrefix(r.URL.Path, "/assets") {
|
||||
return
|
||||
}
|
||||
hlog.FromRequest(r).Info().
|
||||
Str("method", r.Method).
|
||||
Stringer("url", r.URL).
|
||||
Int("status", status).
|
||||
Int("size", size).
|
||||
Dur("duration", duration).
|
||||
Send()
|
||||
}),
|
||||
hlog.RemoteAddrHandler("ip"),
|
||||
hlog.UserAgentHandler("user_agent"),
|
||||
hlog.RefererHandler("referer"),
|
||||
hlog.RequestIDHandler("req_id", "Request-Id"),
|
||||
)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue