github.com/wangyougui/gf/v2@v2.6.5/net/gclient/gclient_middleware.go (about)

     1  package gclient
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/wangyougui/gf/v2/os/gctx"
     7  )
     8  
     9  // HandlerFunc middleware handler func
    10  type HandlerFunc = func(c *Client, r *http.Request) (*Response, error)
    11  
    12  // clientMiddleware is the plugin for http client request workflow management.
    13  type clientMiddleware struct {
    14  	client       *Client       // http client.
    15  	handlers     []HandlerFunc // mdl handlers.
    16  	handlerIndex int           // current handler index.
    17  	resp         *Response     // save resp.
    18  	err          error         // save err.
    19  }
    20  
    21  const clientMiddlewareKey gctx.StrKey = "__clientMiddlewareKey"
    22  
    23  // Use adds one or more middleware handlers to client.
    24  func (c *Client) Use(handlers ...HandlerFunc) *Client {
    25  	c.middlewareHandler = append(c.middlewareHandler, handlers...)
    26  	return c
    27  }
    28  
    29  // Next calls the next middleware.
    30  // This should only be call in HandlerFunc.
    31  func (c *Client) Next(req *http.Request) (*Response, error) {
    32  	if v := req.Context().Value(clientMiddlewareKey); v != nil {
    33  		if m, ok := v.(*clientMiddleware); ok {
    34  			return m.Next(req)
    35  		}
    36  	}
    37  	return c.callRequest(req)
    38  }
    39  
    40  // Next calls the next middleware handler.
    41  func (m *clientMiddleware) Next(req *http.Request) (resp *Response, err error) {
    42  	if m.err != nil {
    43  		return m.resp, m.err
    44  	}
    45  	if m.handlerIndex < len(m.handlers) {
    46  		m.handlerIndex++
    47  		m.resp, m.err = m.handlers[m.handlerIndex](m.client, req)
    48  	}
    49  	return m.resp, m.err
    50  }