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

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)1314// MethodQuery is the HTTP QUERY method defined by RFC 10008. It is declared15// 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"1819var (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,27		http.MethodTrace, MethodQuery,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}5758// 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}7374// RouterGroup is used internally to configure router, a RouterGroup is associated with75// a prefix and an array of handlers (middleware).76type RouterGroup struct {77	Handlers HandlersChain78	basePath string79	engine   *Engine80	root     bool81}8283var (84	_ IRouter      = (*RouterGroup)(nil)85	_ IQueryRoutes = (*RouterGroup)(nil)86)8788// 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).127//128// It panics if httpMethod is not a valid HTTP method (uppercase ASCII letters only).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}170171// QUERY is a shortcut for router.Handle("QUERY", path, handlers).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.176func (group *RouterGroup) QUERY(relativePath string, handlers ...HandlerFunc) IRoutes {177	return group.handle(MethodQuery, relativePath, handlers)178}179180// Any registers a route that matches all the HTTP methods.181// GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE, QUERY.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}206207// StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead.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()238// It panics if relativePath contains URL parameters (: or *).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}