123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- package wisp
- import (
- "net/http"
- "path"
- "slices"
- "strings"
- )
- type Group struct {
- prefix string
- parent *Wisp
- middlewares []Middleware
- }
- func (g *Group) Use(m ...Middleware) {
- g.middlewares = append(g.middlewares, m...)
- }
- func (g *Group) GET(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodGet, path, h, mws...)
- }
- func (g *Group) POST(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodPost, path, h, mws...)
- }
- func (g *Group) PUT(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodPut, path, h, mws...)
- }
- func (g *Group) DELETE(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodDelete, path, h, mws...)
- }
- func (g *Group) PATCH(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodPatch, path, h, mws...)
- }
- func (g *Group) OPTIONS(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodOptions, path, h, mws...)
- }
- func (g *Group) HEAD(path string, h Handler, mws ...Middleware) {
- g.handle(http.MethodHead, path, h, mws...)
- }
- func (g *Group) Static(relativePath, root string) {
- if !strings.HasPrefix(relativePath, "/") {
- relativePath = "/" + relativePath
- }
- fullPath := path.Join(g.prefix, relativePath)
- fileServer := http.StripPrefix(fullPath, http.FileServer(http.Dir(root)))
- handler := func(ctx *Context) error {
- fileServer.ServeHTTP(ctx.Response(), ctx.Request())
- return nil
- }
- g.GET(relativePath+"/*filepath", handler)
- }
- func (g *Group) handle(method, path string, h Handler, routeMws ...Middleware) {
- allMws := slices.Clone(g.parent.middlewares)
- allMws = append(allMws, g.middlewares...)
- allMws = append(allMws, routeMws...)
- h = g.parent.chainMiddlewares(h, allMws)
- fullPath := g.prefix + path
- finalHandler := g.parent.makeHTTPRouterHandler(h)
- switch method {
- case http.MethodGet:
- g.parent.router.GET(fullPath, finalHandler)
- case http.MethodPost:
- g.parent.router.POST(fullPath, finalHandler)
- case http.MethodPut:
- g.parent.router.PUT(fullPath, finalHandler)
- case http.MethodDelete:
- g.parent.router.DELETE(fullPath, finalHandler)
- case http.MethodPatch:
- g.parent.router.PATCH(fullPath, finalHandler)
- case http.MethodOptions:
- g.parent.router.OPTIONS(fullPath, finalHandler)
- case http.MethodHead:
- g.parent.router.HEAD(fullPath, finalHandler)
- }
- }
|