github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/group.go (about)

     1  package don
     2  
     3  import (
     4  	"net/http"
     5  	"strings"
     6  
     7  	"github.com/abemedia/go-don/internal/byteconv"
     8  	"github.com/abemedia/httprouter"
     9  	"github.com/valyala/fasthttp"
    10  )
    11  
    12  type group struct {
    13  	r      *API
    14  	prefix string
    15  }
    16  
    17  func (g *group) Get(path string, handle httprouter.Handle) {
    18  	g.Handle(http.MethodGet, path, handle)
    19  }
    20  
    21  func (g *group) Post(path string, handle httprouter.Handle) {
    22  	g.Handle(http.MethodPost, path, handle)
    23  }
    24  
    25  func (g *group) Put(path string, handle httprouter.Handle) {
    26  	g.Handle(http.MethodPut, path, handle)
    27  }
    28  
    29  func (g *group) Patch(path string, handle httprouter.Handle) {
    30  	g.Handle(http.MethodPatch, path, handle)
    31  }
    32  
    33  func (g *group) Delete(path string, handle httprouter.Handle) {
    34  	g.Handle(http.MethodDelete, path, handle)
    35  }
    36  
    37  func (g *group) Handle(method, path string, handle httprouter.Handle) {
    38  	g.r.Handle(method, g.prefix+path, handle)
    39  }
    40  
    41  func (g *group) Handler(method, path string, handle http.Handler) {
    42  	g.r.Handler(method, g.prefix+path, handle)
    43  }
    44  
    45  func (g *group) HandleFunc(method, path string, handle http.HandlerFunc) {
    46  	g.Handler(method, path, handle)
    47  }
    48  
    49  func (g *group) Group(path string) Router {
    50  	return &group{prefix: g.prefix + path, r: g.r}
    51  }
    52  
    53  func (g *group) Use(mw ...Middleware) {
    54  	g.r.Use(func(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    55  		mwNext := next
    56  		for _, fn := range mw {
    57  			mwNext = fn(mwNext)
    58  		}
    59  
    60  		return func(ctx *fasthttp.RequestCtx) {
    61  			// Only use the middleware if path belongs to group.
    62  			if strings.HasPrefix(byteconv.Btoa(ctx.Path()), g.prefix) {
    63  				mwNext(ctx)
    64  			} else {
    65  				next(ctx)
    66  			}
    67  		}
    68  	})
    69  }