Skip to content
Myr

routergroup.go

This file

Path

routergroup.go

295 lines · 10.5 KiB · Go

Last changed by

feat(routergroup): include HTTP QUERY method in Any (#4878)adam maguedbefore adoptione8f2496

History of this file

Take it

The walk stopped after 200 commits: lines older than cf32d2d point at it.

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 1–13why, one step back
1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8 "net/http"9 "path"10 "regexp"11 "strings"12)13

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf

lines 14–18why, one step back
14// MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared
15// here because the standard library does not provide http.MethodQuery yet.16// Once it does, this constant keeps the same value and stays valid.17const MethodQuery = "QUERY"18

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 19–26why, one step back
19var (
20 // regEnLetter matches english letters for http method name21 regEnLetter = regexp.MustCompile("^[A-Z]+$")2223 // anyMethods for RouterGroup Any method24 anyMethods = []string{25 http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch,26 http.MethodHead, http.MethodOptions, http.MethodDelete, http.MethodConnect,

feat(routergroup): include HTTP QUERY method in Any (#4878)adam maguedbefore adoptione8f2496

line 27why, one step back
27 http.MethodTrace, MethodQuery,

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 28–57why, one step back
28 }
29)3031// IRouter defines all router handle interface includes single and group router.32type IRouter interface {33 IRoutes34 Group(string, ...HandlerFunc) *RouterGroup35}3637// IRoutes defines all router handle interface.38type IRoutes interface {39 Use(...HandlerFunc) IRoutes4041 Handle(string, string, ...HandlerFunc) IRoutes42 Any(string, ...HandlerFunc) IRoutes43 GET(string, ...HandlerFunc) IRoutes44 POST(string, ...HandlerFunc) IRoutes45 DELETE(string, ...HandlerFunc) IRoutes46 PATCH(string, ...HandlerFunc) IRoutes47 PUT(string, ...HandlerFunc) IRoutes48 OPTIONS(string, ...HandlerFunc) IRoutes49 HEAD(string, ...HandlerFunc) IRoutes50 Match([]string, string, ...HandlerFunc) IRoutes5152 StaticFile(string, string) IRoutes53 StaticFileFS(string, string, http.FileSystem) IRoutes54 Static(string, string) IRoutes55 StaticFS(string, http.FileSystem) IRoutes56}57

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf

lines 58–73why, one step back
58// IQueryRoutes defines the router handle interface for the HTTP QUERY method.
59//60// It is deliberately kept out of IRoutes: adding a method to IRoutes would61// break every type outside of Gin that implements it, such as test doubles and62// wrappers. Type assert when you only hold an IRoutes value:63//64// if q, ok := routes.(gin.IQueryRoutes); ok {65// q.QUERY("/search", handler)66// }67//68// *gin.RouterGroup and *gin.Engine satisfy this interface, so the assertion is69// only needed when the concrete type has been erased.70type IQueryRoutes interface {71 QUERY(string, ...HandlerFunc) IRoutes72}73

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 74–82why, one step back
74// RouterGroup is used internally to configure router, a RouterGroup is associated with
75// a prefix and an array of handlers (middleware).76type RouterGroup struct {77 Handlers HandlersChain78 basePath string79 engine *Engine80 root bool81}82

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf

lines 83–86why, one step back
83var (
84 _ IRouter = (*RouterGroup)(nil)85 _ IQueryRoutes = (*RouterGroup)(nil)86)

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 87–126why, one step back
87
88// Use adds middleware to the group, see example code in GitHub.89func (group *RouterGroup) Use(middleware ...HandlerFunc) IRoutes {90 group.Handlers = append(group.Handlers, middleware...)91 return group.returnObj()92}9394// Group creates a new router group. You should add all the routes that have common middlewares or the same path prefix.95// For example, all the routes that use a common middleware for authorization could be grouped.96func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {97 return &RouterGroup{98 Handlers: group.combineHandlers(handlers),99 basePath: group.calculateAbsolutePath(relativePath),100 engine: group.engine,101 }102}103104// BasePath returns the base path of router group.105// For example, if v := router.Group("/rest/n/v1/api"), v.BasePath() is "/rest/n/v1/api".106func (group *RouterGroup) BasePath() string {107 return group.basePath108}109110func (group *RouterGroup) handle(httpMethod, relativePath string, handlers HandlersChain) IRoutes {111 absolutePath := group.calculateAbsolutePath(relativePath)112 handlers = group.combineHandlers(handlers)113 group.engine.addRoute(httpMethod, absolutePath, handlers)114 return group.returnObj()115}116117// Handle registers a new request handle and middleware with the given path and method.118// The last handler should be the real handler, the other ones should be middleware that can and should be shared among different routes.119// See the example code in GitHub.120//121// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut122// functions can be used.123//124// This function is intended for bulk loading and to allow the usage of less125// frequently used, non-standardized or custom methods (e.g. for internal126// communication with a proxy).

docs: document panic conditions in Handle, StaticFS, and Bind (#4797)Ruben Paribefore adoptionb52df1f

lines 127–128why, one step back
127//
128// It panics if httpMethod is not a valid HTTP method (uppercase ASCII letters only).

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 129–170why, one step back
129func (group *RouterGroup) Handle(httpMethod, relativePath string, handlers ...HandlerFunc) IRoutes {
130 if matched := regEnLetter.MatchString(httpMethod); !matched {131 panic("http method " + httpMethod + " is not valid")132 }133 return group.handle(httpMethod, relativePath, handlers)134}135136// POST is a shortcut for router.Handle("POST", path, handlers).137func (group *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) IRoutes {138 return group.handle(http.MethodPost, relativePath, handlers)139}140141// GET is a shortcut for router.Handle("GET", path, handlers).142func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {143 return group.handle(http.MethodGet, relativePath, handlers)144}145146// DELETE is a shortcut for router.Handle("DELETE", path, handlers).147func (group *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) IRoutes {148 return group.handle(http.MethodDelete, relativePath, handlers)149}150151// PATCH is a shortcut for router.Handle("PATCH", path, handlers).152func (group *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) IRoutes {153 return group.handle(http.MethodPatch, relativePath, handlers)154}155156// PUT is a shortcut for router.Handle("PUT", path, handlers).157func (group *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) IRoutes {158 return group.handle(http.MethodPut, relativePath, handlers)159}160161// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handlers).162func (group *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) IRoutes {163 return group.handle(http.MethodOptions, relativePath, handlers)164}165166// HEAD is a shortcut for router.Handle("HEAD", path, handlers).167func (group *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) IRoutes {168 return group.handle(http.MethodHead, relativePath, handlers)169}170

feat(router): add QUERY method shortcut for RFC 10008 (#4830)Jia-ben00before adoption2a1a14f

line 171why, one step back
171// QUERY is a shortcut for router.Handle("QUERY", path, handlers).

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf

lines 172–175why, one step back
172//
173// QUERY is the safe and idempotent method defined by RFC 10008 that carries its174// query in the request body. The body is read like any other body, for example175// with c.ShouldBindJSON.

feat(router): add QUERY method shortcut for RFC 10008 (#4830)Jia-ben00before adoption2a1a14f

line 176why, one step back
176func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes {

feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf

line 177why, one step back
177 return group.handle(MethodQuery, relativePath, handlers)

feat(router): add QUERY method shortcut for RFC 10008 (#4830)Jia-ben00before adoption2a1a14f

lines 178–179why, one step back
178}
179

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

line 180why, one step back
180// Any registers a route that matches all the HTTP methods.

feat(routergroup): include HTTP QUERY method in Any (#4878)adam maguedbefore adoptione8f2496

line 181why, one step back
181// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE, QUERY.

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 182–206why, one step back
182func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {
183 for _, method := range anyMethods {184 group.handle(method, relativePath, handlers)185 }186187 return group.returnObj()188}189190// Match registers a route that matches the specified methods that you declared.191func (group *RouterGroup) Match(methods []string, relativePath string, handlers ...HandlerFunc) IRoutes {192 for _, method := range methods {193 group.handle(method, relativePath, handlers)194 }195196 return group.returnObj()197}198199// StaticFile registers a single route in order to serve a single file of the local filesystem.200// router.StaticFile("favicon.ico", "./resources/favicon.ico")201func (group *RouterGroup) StaticFile(relativePath, filepath string) IRoutes {202 return group.staticFileHandler(relativePath, func(c *Context) {203 c.File(filepath)204 })205}206

fix: Correct typos, improve documentation clarity, and remove dead code (#4511)Mahan Adhikaribefore adoption8e07d37

line 207why, one step back
207// StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 208–237why, one step back
208// router.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})
209// Gin by default uses: gin.Dir()210func (group *RouterGroup) StaticFileFS(relativePath, filepath string, fs http.FileSystem) IRoutes {211 return group.staticFileHandler(relativePath, func(c *Context) {212 c.FileFromFS(filepath, fs)213 })214}215216func (group *RouterGroup) staticFileHandler(relativePath string, handler HandlerFunc) IRoutes {217 if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {218 panic("URL parameters can not be used when serving a static file")219 }220 group.GET(relativePath, handler)221 group.HEAD(relativePath, handler)222 return group.returnObj()223}224225// Static serves files from the given file system root.226// Internally a http.FileServer is used, therefore http.NotFound is used instead227// of the Router's NotFound handler.228// To use the operating system's file system implementation,229// use :230//231// router.Static("/static", "/var/www")232func (group *RouterGroup) Static(relativePath, root string) IRoutes {233 return group.StaticFS(relativePath, Dir(root, false))234}235236// StaticFS works just like `Static()` but a custom `http.FileSystem` can be used instead.237// Gin by default uses: gin.Dir()

docs: document panic conditions in Handle, StaticFS, and Bind (#4797)Ruben Paribefore adoptionb52df1f

line 238why, one step back
238// It panics if relativePath contains URL parameters (: or *).

chore(deps): bump github.com/pelletier/go-toml/v2 from 2.2.2 to 2.2.4 (#4212)dependabot[bot]before adoptioncf32d2d

lines 239–295why, one step back
239func (group *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) IRoutes {
240 if strings.Contains(relativePath, ":") || strings.Contains(relativePath, "*") {241 panic("URL parameters can not be used when serving a static folder")242 }243 handler := group.createStaticHandler(relativePath, fs)244 urlPattern := path.Join(relativePath, "/*filepath")245246 // Register GET and HEAD handlers247 group.GET(urlPattern, handler)248 group.HEAD(urlPattern, handler)249 return group.returnObj()250}251252func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {253 absolutePath := group.calculateAbsolutePath(relativePath)254 fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))255256 return func(c *Context) {257 if _, noListing := fs.(*OnlyFilesFS); noListing {258 c.Writer.WriteHeader(http.StatusNotFound)259 }260261 file := c.Param("filepath")262 // Check if file exists and/or if we have permission to access it263 f, err := fs.Open(file)264 if err != nil {265 c.Writer.WriteHeader(http.StatusNotFound)266 c.handlers = group.engine.noRoute267 // Reset index268 c.index = -1269 return270 }271 f.Close()272273 fileServer.ServeHTTP(c.Writer, c.Request)274 }275}276277func (group *RouterGroup) combineHandlers(handlers HandlersChain) HandlersChain {278 finalSize := len(group.Handlers) + len(handlers)279 assert1(finalSize < int(abortIndex), "too many handlers")280 mergedHandlers := make(HandlersChain, finalSize)281 copy(mergedHandlers, group.Handlers)282 copy(mergedHandlers[len(group.Handlers):], handlers)283 return mergedHandlers284}285286func (group *RouterGroup) calculateAbsolutePath(relativePath string) string {287 return joinPaths(group.basePath, relativePath)288}289290func (group *RouterGroup) returnObj() IRoutes {291 if group.root {292 return group.engine293 }294 return group295}