github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_server_router_middleware.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/wangyougui/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"context"
    11  	"reflect"
    12  
    13  	"github.com/wangyougui/gf/v2/debug/gdebug"
    14  )
    15  
    16  const (
    17  	// The default route pattern for global middleware.
    18  	defaultMiddlewarePattern = "/*"
    19  )
    20  
    21  // BindMiddleware registers one or more global middleware to the server.
    22  // Global middleware can be used standalone without service handler, which intercepts all dynamic requests
    23  // before or after service handler. The parameter `pattern` specifies what route pattern the middleware intercepts,
    24  // which is usually a "fuzzy" pattern like "/:name", "/*any" or "/{field}".
    25  func (s *Server) BindMiddleware(pattern string, handlers ...HandlerFunc) {
    26  	var (
    27  		ctx = context.TODO()
    28  	)
    29  	for _, handler := range handlers {
    30  		s.setHandler(ctx, setHandlerInput{
    31  			Prefix:  "",
    32  			Pattern: pattern,
    33  			HandlerItem: &HandlerItem{
    34  				Type: HandlerTypeMiddleware,
    35  				Name: gdebug.FuncPath(handler),
    36  				Info: handlerFuncInfo{
    37  					Func: handler,
    38  					Type: reflect.TypeOf(handler),
    39  				},
    40  			},
    41  		})
    42  	}
    43  }
    44  
    45  // BindMiddlewareDefault registers one or more global middleware to the server using default pattern "/*".
    46  // Global middleware can be used standalone without service handler, which intercepts all dynamic requests
    47  // before or after service handler.
    48  func (s *Server) BindMiddlewareDefault(handlers ...HandlerFunc) {
    49  	var (
    50  		ctx = context.TODO()
    51  	)
    52  	for _, handler := range handlers {
    53  		s.setHandler(ctx, setHandlerInput{
    54  			Prefix:  "",
    55  			Pattern: defaultMiddlewarePattern,
    56  			HandlerItem: &HandlerItem{
    57  				Type: HandlerTypeMiddleware,
    58  				Name: gdebug.FuncPath(handler),
    59  				Info: handlerFuncInfo{
    60  					Func: handler,
    61  					Type: reflect.TypeOf(handler),
    62  				},
    63  			},
    64  		})
    65  	}
    66  }
    67  
    68  // Use is the alias of BindMiddlewareDefault.
    69  // See BindMiddlewareDefault.
    70  func (s *Server) Use(handlers ...HandlerFunc) {
    71  	s.BindMiddlewareDefault(handlers...)
    72  }