Skip to content

Commit

Permalink
♻️ refactor: refactoring the extra pkg, move to subdir pkg/
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Jun 26, 2023
1 parent 4a5ac35 commit 266d634
Show file tree
Hide file tree
Showing 23 changed files with 47 additions and 52 deletions.
File renamed without changes.
File renamed without changes.
4 changes: 2 additions & 2 deletions binding/binder.go → pkg/binding/binder.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ var (
}
)

// BinderFunc implements the Binder interface
// Name implements the Binder interface
func (fn BinderFunc) Name() string {
return "unknown"
}

// BinderFunc implements the Binder interface
// Bind implements the Binder interface
func (fn BinderFunc) Bind(r *http.Request, obj any) error {
return fn(r, obj)
}
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
1 change: 0 additions & 1 deletion binding/form.go → pkg/binding/form.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,5 @@ func DecodeUrlValues(values map[string][]string, ptr any, tagName string) error
if err := dec.Decode(values, ptr); err != nil {
return err
}

return validating(ptr)
}
File renamed without changes.
File renamed without changes.
File renamed without changes.
7 changes: 1 addition & 6 deletions binding/validate.go → pkg/binding/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,7 @@ type stdValidator struct{}
// Validate the struct data, if fail return error
func (sv *stdValidator) Validate(obj any) error {
v := validate.New(obj)
if v.Validate() {
return nil
}

return v.Errors
return v.ValidateE()
}

// DisableValidator for data binding
Expand All @@ -32,6 +28,5 @@ func validating(obj any) error {
if Validator == nil {
return nil
}

return Validator.Validate(obj)
}
File renamed without changes.
27 changes: 17 additions & 10 deletions handlers/request_logger.go → pkg/handlers/console_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,21 @@ import (
"github.com/gookit/rux"
)

// RequestLogger middleware.
func RequestLogger() rux.HandlerFunc {
skip := map[string]int{
// "/": 1,
"/health": 1,
"/status": 1,
// RequestLogger middleware. alias of ConsoleLogger
var RequestLogger = ConsoleLogger
var IgnorePaths = []string{
"/health",
"/status",
}

// ConsoleLogger middleware.
func ConsoleLogger(ignorePaths ...string) rux.HandlerFunc {
IgnorePaths = append(IgnorePaths, ignorePaths...)
skipPathMap := map[string]int{}
for _, path := range IgnorePaths {
skipPathMap[path] = 1
}

// open color
color.ForceOpenColor()

Expand All @@ -28,11 +36,10 @@ func RequestLogger() rux.HandlerFunc {

// Process request
c.Next()

path := c.URL().Path

// Log only when path is not being skipped
if _, ok := skip[path]; ok {
if _, ok := skipPathMap[path]; ok {
return
}

Expand All @@ -47,10 +54,10 @@ func RequestLogger() rux.HandlerFunc {
codeColor := colorForStatus(c.StatusCode())

color.Printf(
// 2006-01-02T15:04:05 [rux] GET /articles 200 10.0.0.1 "use-agent" 0.034ms
// 2006/01/02T15:04:05 [rux] GET /articles 200 10.0.0.1 "use-agent" 0.034ms
// `%s %s %s %d %s "%s" %sms` + "\n",
"%s [%s] %s [%s] %s %sms\n",
start.Format("2006/01/02T15:04:05"),
start.Format("2006/01/02T15:04:05.000"),
c.ClientIP(),
mColor.Render(c.Req.Method),
codeColor.Render(c.StatusCode()),
Expand Down
6 changes: 3 additions & 3 deletions handlers/handlers.go → pkg/handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ const (
HTTPMethodOverrideHeader = "X-HTTP-Method-Override"
// HTTPMethodOverrideFormKey is a commonly used HTML form key to override a request method
HTTPMethodOverrideFormKey = "_method"
// OriginalMethodContextKey is a commonly for record old original request method
// OriginalMethodContextKey record old original request method
OriginalMethodContextKey contextKey = "originalMethod"
)

// HTTPMethodOverrideHandler wraps and returns a http.Handler which checks for
// the X-HTTP-Method-Override header or the _method form key, and overrides (if
// valid) request.Method with its value.
//
// It is ref from the https://github.com/gorilla/handlers
// Refer from the https://github.com/gorilla/handlers
func HTTPMethodOverrideHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
Expand Down Expand Up @@ -67,6 +67,6 @@ type (
)

// DefaultSkipper returns false which processes the middleware.
func DefaultSkipper(*rux.Context) bool {
func DefaultSkipper(_ *rux.Context) bool {
return false
}
File renamed without changes.
46 changes: 19 additions & 27 deletions handlers/middlewares.go → pkg/handlers/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ package handlers

import (
"context"
"crypto/md5"
"encoding/hex"
"fmt"
"net/http"
"time"

"github.com/gookit/goutil/mathutil"
"github.com/gookit/rux"
)

Expand All @@ -25,21 +24,22 @@ func IgnoreFavIcon() rux.HandlerFunc {
}

// GenRequestID for the request
func GenRequestID() rux.HandlerFunc {
func GenRequestID(key string) rux.HandlerFunc {
return func(c *rux.Context) {
reqID := genMd5(fmt.Sprintf("rux-%d", time.Now().Nanosecond()))
now := time.Now()
val := fmt.Sprintf("r%xq%d", now.UnixMicro(), mathutil.RandIntWithSeed(1000, 9999, int64(now.Nanosecond())))
// add reqID to context
c.Set("reqID", reqID)
c.Set(key, val)
}
}

// HTTPBasicAuth for the request
//
// Usage:
//
// r.GET("/auth", func(c *rux.Context) {
// c.WriteString("hello")
// }, HTTPBasicAuth(map[string]string{"testuser": "123"}))
//
func HTTPBasicAuth(accounts map[string]string) rux.HandlerFunc {
return func(c *rux.Context) {
user, pwd, ok := c.Req.BasicAuth()
Expand Down Expand Up @@ -79,28 +79,28 @@ func PanicsHandler() rux.HandlerFunc {
}

// Timeout is a middleware for handle logic.
// the method is refer from "github.com/go-chi/chi/middleware"
// the method is referred from "github.com/go-chi/chi/middleware"
//
// It's required that you select the ctx.Done() channel to check for the signal
// if the context has reached its deadline and return, otherwise the timeout
// signal will be just ignored.
//
// ie. a route/handler may look like:
// a route/handler may look like:
//
// r.GET("/long", func(c *rux.Context) {
// ctx := c.Req.Context()
// processTime := time.Duration(rand.Intn(4)+1) * time.Second
// r.GET("/long", func(c *rux.Context) {
// ctx := c.Req.Context()
// processTime := time.Duration(rand.Intn(4)+1) * time.Second
//
// select {
// case <-ctx.Done():
// return
// select {
// case <-ctx.Done():
// return
//
// case <-time.After(processTime):
// // The above channel simulates some hard work.
// }
// case <-time.After(processTime):
// // The above channel simulates some hard work.
// }
//
// c.WriteBytes([]byte("done"))
// })
// c.WriteBytes([]byte("done"))
// })
func Timeout(timeout time.Duration) rux.HandlerFunc {
return func(c *rux.Context) {
ctx, cancel := context.WithTimeout(c.Req.Context(), timeout)
Expand All @@ -116,11 +116,3 @@ func Timeout(timeout time.Duration) rux.HandlerFunc {
c.Next()
}
}

// genMd5 生成32位md5字串
func genMd5(s string) string {
h := md5.New()
h.Write([]byte(s))

return hex.EncodeToString(h.Sum(nil))
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"strings"
"testing"

"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/testutil"
"github.com/gookit/goutil/testutil/assert"
"github.com/gookit/rux"
Expand All @@ -22,10 +23,11 @@ func TestSomeMiddleware(t *testing.T) {

// add reqID to context
r.GET("/rid", func(c *rux.Context) {
rid, ok := c.Get("reqID")
rid, ok := c.Get("req_id")
art.True(ok)
art.Len(rid.(string), 32)
}).Use(GenRequestID())
art.NotEmpty(rid.(string))
dump.P(rid)
}).Use(GenRequestID("req_id"))

w := mockRequest(r, "GET", "/rid", nil)
art.Eq(200, w.Code)
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

0 comments on commit 266d634

Please sign in to comment.