github.com/Mrs4s/go-cqhttp@v1.2.0/modules/api/caller.go (about)

     1  // Package api implements the API route for servers.
     2  package api
     3  
     4  import (
     5  	"github.com/tidwall/gjson"
     6  
     7  	"github.com/Mrs4s/go-cqhttp/coolq"
     8  	"github.com/Mrs4s/go-cqhttp/global"
     9  	"github.com/Mrs4s/go-cqhttp/pkg/onebot"
    10  )
    11  
    12  //go:generate go run ./../../cmd/api-generator -pkg api -path=./../../coolq/api.go,./../../coolq/api_v12.go -o api.go
    13  
    14  // Getter 参数获取
    15  type Getter interface {
    16  	Get(string) gjson.Result
    17  }
    18  
    19  // Handler 中间件
    20  type Handler func(action string, spe *onebot.Spec, p Getter) global.MSG
    21  
    22  // Caller api route caller
    23  type Caller struct {
    24  	bot      *coolq.CQBot
    25  	handlers []Handler
    26  }
    27  
    28  // Call specific API
    29  func (c *Caller) Call(action string, spec *onebot.Spec, p Getter) global.MSG {
    30  	for _, fn := range c.handlers {
    31  		if ret := fn(action, spec, p); ret != nil {
    32  			return ret
    33  		}
    34  	}
    35  	return c.call(action, spec, p)
    36  }
    37  
    38  // Use add handlers to the API caller
    39  func (c *Caller) Use(middlewares ...Handler) {
    40  	c.handlers = append(c.handlers, middlewares...)
    41  }
    42  
    43  // NewCaller create a new API caller
    44  func NewCaller(bot *coolq.CQBot) *Caller {
    45  	return &Caller{
    46  		bot:      bot,
    47  		handlers: make([]Handler, 0),
    48  	}
    49  }