package xybot import ( "encoding/json" "errors" "slices" "strings" "gitee.ltd/lxh/xybot/core" "gitee.ltd/lxh/xybot/friend" "gitee.ltd/lxh/xybot/group" "gitee.ltd/lxh/xybot/hongbao" "gitee.ltd/lxh/xybot/login" "gitee.ltd/lxh/xybot/message" "gitee.ltd/lxh/xybot/tool" "gitee.ltd/lxh/xybot/user" "github.com/go-resty/resty/v2" ) type Client struct { // HTTP客户端 httpClient *resty.Client // 功能模块 Login login.API Friend friend.API Group group.API Message message.API User user.API HongBao hongbao.API Tool tool.API } // NewClient // @description: 创建新的微信API客户端 // @param wxId string 机器人微信ID // @param baseUrl string 机器人接口基础URL // @param debug bool 是否开启调试模式 // @return cli // @return err func NewClient(wxId, baseUrl string, debug bool) (cli *Client, err error) { if baseUrl == "" { err = errors.New("baseUrl 不得为空,格式为: http://10.0.0.11:9001") return } // 如果URL没有以http://或https://开头,自动添加http:// if !strings.HasPrefix(baseUrl, "http://") && !strings.HasPrefix(baseUrl, "https://") { baseUrl = "http://" + baseUrl } // 设置一下机器人微信Id的值 wxInfo := core.NewInfo(wxId) cli = &Client{} cli.httpClient = resty.New(). SetBaseURL(baseUrl). SetDebug(debug). SetHeader("User-Agent", "lxh-xybot-client"). SetJSONMarshaler(json.Marshal). SetJSONUnmarshaler(json.Unmarshal). OnBeforeRequest(requestPreCheck) cli.Login = login.New(cli.httpClient, wxInfo) cli.Friend = friend.New(cli.httpClient, wxInfo) cli.Group = group.New(cli.httpClient, wxInfo) cli.Message = message.New(cli.httpClient, wxInfo) cli.User = user.New(cli.httpClient, wxInfo) cli.HongBao = hongbao.New(cli.httpClient, wxInfo) cli.Tool = tool.New(cli.httpClient, wxInfo) return } // requestPreCheck // @description: 请求前置检查 // @param _ *resty.Client // @param req *resty.Request // @return err error func requestPreCheck(_ *resty.Client, req *resty.Request) (err error) { // 在这儿判断指定请求地址的时候WxId是否有值 whiteUrls := []string{"/GetQRCode", "/CheckUuid", "/IsRunning", "/CheckDatabaseOK"} if slices.Contains(whiteUrls, req.URL) { // 如果是白名单请求,直接返回 return nil } if req.Header.Get("WeChatId") == "" { // 如果WxId为空,直接返回 return errors.New("wxId不能为空") } return nil }