diff --git a/library.go b/library.go index 606a5545..083b7d4b 100644 --- a/library.go +++ b/library.go @@ -1,5 +1,5 @@ package go_library func Version() string { - return "v1.0.50" + return "1.0.51" } diff --git a/service/dingdanxia/jd.jy_order_details.go b/service/dingdanxia/jd.jy_order_details.go index eb9897b2..223ed364 100644 --- a/service/dingdanxia/jd.jy_order_details.go +++ b/service/dingdanxia/jd.jy_order_details.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -39,11 +40,11 @@ func newJdJyOrderDetailsResult(result JdJyOrderDetailsResponse, body []byte, htt } // JdJyOrderDetails 【官方不维护】 京佣订单 -func (c *Client) JdJyOrderDetails(notMustParams ...gorequest.Params) *JdJyOrderDetailsResult { +func (c *Client) JdJyOrderDetails(ctx context.Context, notMustParams ...gorequest.Params) *JdJyOrderDetailsResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/jd/jy_order_details", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/jd/jy_order_details", params, http.MethodPost) // 定义 var response JdJyOrderDetailsResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingdanxia/jd.order_details2.go b/service/dingdanxia/jd.order_details2.go index d38373ea..85653e71 100644 --- a/service/dingdanxia/jd.order_details2.go +++ b/service/dingdanxia/jd.order_details2.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -8,11 +9,11 @@ import ( // JdOrderDetails2 【官方不维护】 京东联盟订单行查询 // https://www.dingdanxia.com/doc/180/94 -func (c *Client) JdOrderDetails2(notMustParams ...gorequest.Params) *JdJyOrderDetailsResult { +func (c *Client) JdOrderDetails2(ctx context.Context, notMustParams ...gorequest.Params) *JdJyOrderDetailsResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/jd/order_details2", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/jd/order_details2", params, http.MethodPost) // 定义 var response JdJyOrderDetailsResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingdanxia/request.go b/service/dingdanxia/request.go index cbb66329..2571563d 100644 --- a/service/dingdanxia/request.go +++ b/service/dingdanxia/request.go @@ -1,9 +1,13 @@ package dingdanxia -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) // 请求接口 -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 公共参数 params["apikey"] = c.config.ApiKey @@ -24,17 +28,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/dingdanxia/waimai.meituan_orderid.go b/service/dingdanxia/waimai.meituan_orderid.go index 7035d7a0..fb9bec28 100644 --- a/service/dingdanxia/waimai.meituan_orderid.go +++ b/service/dingdanxia/waimai.meituan_orderid.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -49,13 +50,13 @@ func newWaiMaiMeituanOrderIdResult(result WaiMaiMeituanOrderIdResponse, body []b // WaiMaiMeituanOrderId 美团联盟外卖/闪购/优选/酒店订单查询API(订单号版) // https://www.dingdanxia.com/doc/179/173 -func (c *Client) WaiMaiMeituanOrderId(orderId string) *WaiMaiMeituanOrderIdResult { +func (c *Client) WaiMaiMeituanOrderId(ctx context.Context, orderId string) *WaiMaiMeituanOrderIdResult { // 参数 param := gorequest.NewParams() param.Set("order_id", orderId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/waimai/meituan_orderid", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/waimai/meituan_orderid", params, http.MethodPost) // 定义 var response WaiMaiMeituanOrderIdResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingdanxia/waimai.meituan_orders.go b/service/dingdanxia/waimai.meituan_orders.go index ac159442..ba13e1d8 100644 --- a/service/dingdanxia/waimai.meituan_orders.go +++ b/service/dingdanxia/waimai.meituan_orders.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -40,11 +41,11 @@ func newWaiMaiMeituanOrdersResult(result WaiMaiMeituanOrdersResponse, body []byt // WaiMaiMeituanOrders 美团联盟外卖/闪购/优选/酒店订单查询API // https://www.dingdanxia.com/doc/176/173 -func (c *Client) WaiMaiMeituanOrders(notMustParams ...gorequest.Params) *WaiMaiMeituanOrdersResult { +func (c *Client) WaiMaiMeituanOrders(ctx context.Context, notMustParams ...gorequest.Params) *WaiMaiMeituanOrdersResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/waimai/meituan_orders", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/waimai/meituan_orders", params, http.MethodPost) // 定义 var response WaiMaiMeituanOrdersResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingdanxia/waimai.meituan_privilege.go b/service/dingdanxia/waimai.meituan_privilege.go index 8fe197d1..a5887211 100644 --- a/service/dingdanxia/waimai.meituan_privilege.go +++ b/service/dingdanxia/waimai.meituan_privilege.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -37,7 +38,7 @@ func newWaiMaiMeituanPrivilegeResult(result WaiMaiMeituanPrivilegeResponse, body // WaiMaiMeituanPrivilege 美团外卖CPS推广API接口 // https://www.dingdanxia.com/doc/174/173 -func (c *Client) WaiMaiMeituanPrivilege(sid string, generateWeApp, qrcode bool) *WaiMaiMeituanPrivilegeResult { +func (c *Client) WaiMaiMeituanPrivilege(ctx context.Context, sid string, generateWeApp, qrcode bool) *WaiMaiMeituanPrivilegeResult { // 参数 param := gorequest.NewParams() param.Set("sid", sid) @@ -45,7 +46,7 @@ func (c *Client) WaiMaiMeituanPrivilege(sid string, generateWeApp, qrcode bool) param.Set("qrcode", qrcode) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/waimai/meituan_privilege", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/waimai/meituan_privilege", params, http.MethodPost) // 定义 var response WaiMaiMeituanPrivilegeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingdanxia/waimai.meituan_sg_privilege.go b/service/dingdanxia/waimai.meituan_sg_privilege.go index af29599e..8036009f 100644 --- a/service/dingdanxia/waimai.meituan_sg_privilege.go +++ b/service/dingdanxia/waimai.meituan_sg_privilege.go @@ -1,6 +1,7 @@ package dingdanxia import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -36,7 +37,7 @@ func newWaiMaiMeituanSgPrivilegeResult(result WaiMaiMeituanSgPrivilegeResponse, // WaiMaiMeituanSgPrivilege 美团闪购CPS推广API接口 // https://www.dingdanxia.com/doc/195/173 -func (c *Client) WaiMaiMeituanSgPrivilege(sid string, generateWeApp, qrcode bool) *WaiMaiMeituanSgPrivilegeResult { +func (c *Client) WaiMaiMeituanSgPrivilege(ctx context.Context, sid string, generateWeApp, qrcode bool) *WaiMaiMeituanSgPrivilegeResult { // 参数 param := gorequest.NewParams() param.Set("sid", sid) @@ -44,7 +45,7 @@ func (c *Client) WaiMaiMeituanSgPrivilege(sid string, generateWeApp, qrcode bool param.Set("qrcode", qrcode) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/waimai/meituan_sg_privilege", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/waimai/meituan_sg_privilege", params, http.MethodPost) // 定义 var response WaiMaiMeituanSgPrivilegeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/dingtalk/request.go b/service/dingtalk/request.go index a0cde7d0..7e97a998 100644 --- a/service/dingtalk/request.go +++ b/service/dingtalk/request.go @@ -1,8 +1,12 @@ package dingtalk -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -20,17 +24,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/dingtalk/robot.send.go b/service/dingtalk/robot.send.go index f67142b7..e6d2177b 100644 --- a/service/dingtalk/robot.send.go +++ b/service/dingtalk/robot.send.go @@ -1,6 +1,7 @@ package dingtalk import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,13 +27,13 @@ func newRobotSendResult(result RobotSendResponse, body []byte, http gorequest.Re // RobotSend 自定义机器人 // https://open.dingtalk.com/document/group/custom-robot-access -func (c *Client) RobotSend(notMustParams ...gorequest.Params) *RobotSendResult { +func (c *Client) RobotSend(ctx context.Context, notMustParams ...gorequest.Params) *RobotSendResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 时间 timestamp := time.Now().UnixNano() / 1e6 // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/robot/send?access_token=%s×tamp=%d&sign=%s", c.config.AccessToken, timestamp, c.sign(timestamp)), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/robot/send?access_token=%s×tamp=%d&sign=%s", c.config.AccessToken, timestamp, c.sign(timestamp)), params, http.MethodPost) // 定义 var response RobotSendResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/douyin/api.go b/service/douyin/api.go index 4df21a34..796e0251 100644 --- a/service/douyin/api.go +++ b/service/douyin/api.go @@ -1,6 +1,7 @@ package douyin import ( + "context" "encoding/json" "errors" "github.com/dtapps/go-library/utils/gorequest" @@ -184,7 +185,7 @@ func newAnalysisResult(result AnalysisResponse, body []byte, http gorequest.Resp } // Analysis 抖音解析 -func (c *Client) Analysis(content string) *AnalysisResult { +func (c *Client) Analysis(ctx context.Context, content string) *AnalysisResult { // 提取url var url string @@ -209,7 +210,7 @@ func (c *Client) Analysis(content string) *AnalysisResult { } // 请求 - request, err := c.request("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+itemIds[0], map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+itemIds[0], map[string]interface{}{}, http.MethodGet) // 定义 var response AnalysisResponse diff --git a/service/douyin/request.go b/service/douyin/request.go index b2511f9f..42da6805 100644 --- a/service/douyin/request.go +++ b/service/douyin/request.go @@ -1,10 +1,12 @@ package douyin import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" ) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -25,17 +27,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/eastiot/Iot_api.query_ordered_pkgInfo.go b/service/eastiot/Iot_api.query_ordered_pkgInfo.go index f389ad7f..6c009e57 100644 --- a/service/eastiot/Iot_api.query_ordered_pkgInfo.go +++ b/service/eastiot/Iot_api.query_ordered_pkgInfo.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -34,13 +35,13 @@ func newIotApiQueryOrderedPkgInfoResult(result IotApiQueryOrderedPkgInfoResponse // IotApiQueryOrderedPkgInfo 查询流量卡已订购流量包 // https://www.showdoc.com.cn/916774523755909/5092045889939625 -func (c *Client) IotApiQueryOrderedPkgInfo(simId string) *IotApiQueryOrderedPkgInfoResult { +func (c *Client) IotApiQueryOrderedPkgInfo(ctx context.Context, simId string) *IotApiQueryOrderedPkgInfoResult { // 参数 param := gorequest.NewParams() param.Set("simId", simId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/queryOrderedPkgInfo", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/queryOrderedPkgInfo", params, http.MethodPost) // 定义 var response IotApiQueryOrderedPkgInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/Iot_api.query_sim_pkgInfo.go b/service/eastiot/Iot_api.query_sim_pkgInfo.go index 9ce5c6aa..08f7d8f7 100644 --- a/service/eastiot/Iot_api.query_sim_pkgInfo.go +++ b/service/eastiot/Iot_api.query_sim_pkgInfo.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -40,14 +41,14 @@ func newIotApiQuerySimPkgInfoResult(result IotApiQuerySimPkgInfoResponse, body [ // IotApiQuerySimPkgInfo 流量卡可用流量包查询 // https://www.showdoc.com.cn/916774523755909/4880284631482420 -func (c *Client) IotApiQuerySimPkgInfo(simId string, sd int) *IotApiQuerySimPkgInfoResult { +func (c *Client) IotApiQuerySimPkgInfo(ctx context.Context, simId string, sd int) *IotApiQuerySimPkgInfoResult { // 参数 param := gorequest.NewParams() param.Set("simId", simId) param.Set("sd", sd) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/querySimPkgInfo", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/querySimPkgInfo", params, http.MethodPost) // 定义 var response IotApiQuerySimPkgInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/Iot_api.query_user_pkgInfo.go b/service/eastiot/Iot_api.query_user_pkgInfo.go index 60f61ff9..522fe2d9 100644 --- a/service/eastiot/Iot_api.query_user_pkgInfo.go +++ b/service/eastiot/Iot_api.query_user_pkgInfo.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -39,9 +40,9 @@ func newIotApiQueryUserPkgInfoResult(result IotApiQueryUserPkgInfoResponse, body // IotApiQueryUserPkgInfo 账户可用流量包查询 // https://www.showdoc.com.cn/916774523755909/4850094776758927 -func (c *Client) IotApiQueryUserPkgInfo() *IotApiQueryUserPkgInfoResult { +func (c *Client) IotApiQueryUserPkgInfo(ctx context.Context) *IotApiQueryUserPkgInfoResult { // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/queryUserPkgInfo", map[string]interface{}{}, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/queryUserPkgInfo", map[string]interface{}{}, http.MethodPost) // 定义 var response IotApiQueryUserPkgInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/Iot_api.recharge_sim.go b/service/eastiot/Iot_api.recharge_sim.go index 553df2a3..86d150a6 100644 --- a/service/eastiot/Iot_api.recharge_sim.go +++ b/service/eastiot/Iot_api.recharge_sim.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -24,11 +25,11 @@ func newIotApiRechargeSimResult(result IotApiRechargeSimResponse, body []byte, h // IotApiRechargeSim 单卡流量充值 // https://www.showdoc.com.cn/916774523755909/4880284631482420 -func (c *Client) IotApiRechargeSim(notMustParams ...gorequest.Params) *IotApiRechargeSimResult { +func (c *Client) IotApiRechargeSim(ctx context.Context, notMustParams ...gorequest.Params) *IotApiRechargeSimResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/rechargeSim", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/rechargeSim", params, http.MethodPost) // 定义 var response IotApiRechargeSimResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/api.Iot_api.get_all_sim_type.go b/service/eastiot/api.Iot_api.get_all_sim_type.go index a911ca22..a30a8b0d 100644 --- a/service/eastiot/api.Iot_api.get_all_sim_type.go +++ b/service/eastiot/api.Iot_api.get_all_sim_type.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -29,9 +30,9 @@ func newIotApiGetAllSimTypeResult(result IotApiGetAllSimTypeResponse, body []byt // IotApiGetAllSimType 卡类型列表查询 // https://www.showdoc.com.cn/916774523755909/4858492092033167 -func (c *Client) IotApiGetAllSimType() *IotApiGetAllSimTypeResult { +func (c *Client) IotApiGetAllSimType(ctx context.Context) *IotApiGetAllSimTypeResult { // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/getAllSimType", map[string]interface{}{}, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/getAllSimType", map[string]interface{}{}, http.MethodPost) // 定义 var response IotApiGetAllSimTypeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/lot_api.query_user_balance.go b/service/eastiot/lot_api.query_user_balance.go index bcbb3a88..855bc0f7 100644 --- a/service/eastiot/lot_api.query_user_balance.go +++ b/service/eastiot/lot_api.query_user_balance.go @@ -1,6 +1,7 @@ package eastiot import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -27,9 +28,9 @@ func newIotApiQueryUserBalanceResult(result IotApiQueryUserBalanceResponse, body // IotApiQueryUserBalance 余额查询 // https://www.showdoc.com.cn/916774523755909/4857910459512420 -func (c *Client) IotApiQueryUserBalance() *IotApiQueryUserBalanceResult { +func (c *Client) IotApiQueryUserBalance(ctx context.Context) *IotApiQueryUserBalanceResult { // 请求 - request, err := c.request(apiUrl+"/Api/IotApi/queryUserBalance", map[string]interface{}{}, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/Api/IotApi/queryUserBalance", map[string]interface{}{}, http.MethodPost) // 定义 var response IotApiQueryUserBalanceResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/eastiot/request.go b/service/eastiot/request.go index b1c085ad..b7d9ebe4 100644 --- a/service/eastiot/request.go +++ b/service/eastiot/request.go @@ -1,11 +1,13 @@ package eastiot import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "time" ) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 公共参数 params["appId"] = c.config.AppId @@ -30,17 +32,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/ejiaofei/check_cost.go b/service/ejiaofei/check_cost.go index 68d228d0..3048eef4 100644 --- a/service/ejiaofei/check_cost.go +++ b/service/ejiaofei/check_cost.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,7 +29,7 @@ func newCheckCostResult(result CheckCostResponse, body []byte, http gorequest.Re } // CheckCost 会员订单成本价查询接口 -func (c *Client) CheckCost(orderId string) *CheckCostResult { +func (c *Client) CheckCost(ctx context.Context, orderId string) *CheckCostResult { // 参数 param := gorequest.NewParams() param.Set("orderid", orderId) @@ -36,7 +37,7 @@ func (c *Client) CheckCost(orderId string) *CheckCostResult { // 签名 c.signStr = fmt.Sprintf("userid%vpwd%vorderid%v", c.getUserId(), c.getPwd(), orderId) // 请求 - request, err := c.request(apiUrl+"/checkCost.do", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/checkCost.do", params, http.MethodGet) // 定义 var response CheckCostResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/chongzhi_jkorders.go b/service/ejiaofei/chongzhi_jkorders.go index 3c7a35cc..4e99e190 100644 --- a/service/ejiaofei/chongzhi_jkorders.go +++ b/service/ejiaofei/chongzhi_jkorders.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -36,7 +37,7 @@ func newChOngZhiJkOrdersResult(result ChOngZhiJkOrdersResponse, body []byte, htt // orderid 用户提交的订单号 用户提交的订单号,最长32位(用户保证其唯一性) // face 充值面值 以元为单位,包含10、20、30、50、100、200、300、500 移动联通电信 // account 手机号码 需要充值的手机号码 -func (c *Client) ChOngZhiJkOrders(orderID string, face int, account string) *ChOngZhiJkOrdersResult { +func (c *Client) ChOngZhiJkOrders(ctx context.Context, orderID string, face int, account string) *ChOngZhiJkOrdersResult { // 参数 param := gorequest.NewParams() param.Set("orderid", orderID) @@ -47,7 +48,7 @@ func (c *Client) ChOngZhiJkOrders(orderID string, face int, account string) *ChO // 签名 c.signStr = fmt.Sprintf("userid%vpwd%vorderid%vface%vaccount%vamount1", c.getUserId(), c.getPwd(), orderID, face, account) // 请求 - request, err := c.request(apiUrl+"/chongzhi_jkorders.do", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/chongzhi_jkorders.do", params, http.MethodGet) // 定义 var response ChOngZhiJkOrdersResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/gprs_chongzhi_advance.go b/service/ejiaofei/gprs_chongzhi_advance.go index 0f2a9594..071844bd 100644 --- a/service/ejiaofei/gprs_chongzhi_advance.go +++ b/service/ejiaofei/gprs_chongzhi_advance.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -46,13 +47,13 @@ func newGprsChOngZhiAdvanceResult(result GprsChOngZhiAdvanceResponse, body []byt } // GprsChOngZhiAdvance 流量充值接口 -func (c *Client) GprsChOngZhiAdvance(notMustParams ...gorequest.Params) *GprsChOngZhiAdvanceResult { +func (c *Client) GprsChOngZhiAdvance(ctx context.Context, notMustParams ...gorequest.Params) *GprsChOngZhiAdvanceResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 签名 c.signStr = fmt.Sprintf("userid%vpwd%vorderid%vaccount%vgprs%varea%veffecttime%vvalidity%vtimes%v", c.getUserId(), c.getPwd(), params["orderid"], params["account"], params["gprs"], params["area"], params["effecttime"], params["validity"], params["times"]) // 请求 - request, err := c.request(apiUrl+"/gprsChongzhiAdvance.do", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/gprsChongzhiAdvance.do", params, http.MethodGet) // 定义 var response GprsChOngZhiAdvanceResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/money_jkuser.go b/service/ejiaofei/money_jkuser.go index 2dd5d3a3..19dd4d75 100644 --- a/service/ejiaofei/money_jkuser.go +++ b/service/ejiaofei/money_jkuser.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newMoneyJkUserResult(result MoneyJkUserResponse, body []byte, http goreques } // MoneyJkUser 用户余额查询 -func (c *Client) MoneyJkUser() *MoneyJkUserResult { +func (c *Client) MoneyJkUser(ctx context.Context) *MoneyJkUserResult { // 签名 c.signStr = fmt.Sprintf("userid%vpwd%v", c.getUserId(), c.getPwd()) // 请求 - request, err := c.request(apiUrl+"/money_jkuser.do", map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/money_jkuser.do", map[string]interface{}{}, http.MethodGet) // 定义 var response MoneyJkUserResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/query_jkorders.go b/service/ejiaofei/query_jkorders.go index 9e9f788f..606811a1 100644 --- a/service/ejiaofei/query_jkorders.go +++ b/service/ejiaofei/query_jkorders.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -34,7 +35,7 @@ func newQueryJkOrdersResult(result QueryJkOrdersResponse, body []byte, http gore // QueryJkOrders 通用查询接口 // orderid 用户提交的订单号 用户提交的订单号,最长32位(用户保证其唯一性) -func (c *Client) QueryJkOrders(orderId string) *QueryJkOrdersResult { +func (c *Client) QueryJkOrders(ctx context.Context, orderId string) *QueryJkOrdersResult { // 参数 param := gorequest.NewParams() param.Set("orderid", orderId) @@ -42,7 +43,7 @@ func (c *Client) QueryJkOrders(orderId string) *QueryJkOrdersResult { // 签名 c.signStr = fmt.Sprintf("userid%vpwd%vorderid%v", c.getUserId(), c.getPwd(), orderId) // 请求 - request, err := c.request(apiUrl+"/query_jkorders.do", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/query_jkorders.do", params, http.MethodGet) // 定义 var response QueryJkOrdersResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/query_txproduct.go b/service/ejiaofei/query_txproduct.go index bc1c93a9..afe16492 100644 --- a/service/ejiaofei/query_txproduct.go +++ b/service/ejiaofei/query_txproduct.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -24,11 +25,11 @@ func newQueryTxProductResult(result QueryTxProductResponse, body []byte, http go } // QueryTxProduct 可充值腾讯产品查询 -func (c *Client) QueryTxProduct() *QueryTxProductResult { +func (c *Client) QueryTxProduct(ctx context.Context) *QueryTxProductResult { // 签名 c.signStr = fmt.Sprintf("userid%vpwd%v", c.getUserId(), c.getPwd()) // 请求 - request, err := c.request(apiUrl+"/queryTXproduct.do", map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/queryTXproduct.do", map[string]interface{}{}, http.MethodGet) // 定义 var response QueryTxProductResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/ejiaofei/request.go b/service/ejiaofei/request.go index dc72b181..6d2559dc 100644 --- a/service/ejiaofei/request.go +++ b/service/ejiaofei/request.go @@ -1,12 +1,14 @@ package ejiaofei import ( + "context" "fmt" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gomd5" "github.com/dtapps/go-library/utils/gorequest" ) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 公共参数 params["userid"] = c.getUserId() @@ -31,17 +33,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddlewareXml(request) + go c.log.GormMiddlewareXml(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddlewareXml(request) + go c.log.MongoMiddlewareXml(ctx, request, go_library.Version()) } return request, err diff --git a/service/ejiaofei/txchongzhi.go b/service/ejiaofei/txchongzhi.go index 3a6b80f7..d8ab0498 100644 --- a/service/ejiaofei/txchongzhi.go +++ b/service/ejiaofei/txchongzhi.go @@ -1,6 +1,7 @@ package ejiaofei import ( + "context" "encoding/xml" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -42,13 +43,13 @@ func newTxChOngZhiResult(result TxChOngZhiResponse, body []byte, http gorequest. } // TxChOngZhi 流量充值接口 -func (c *Client) TxChOngZhi(notMustParams ...gorequest.Params) *TxChOngZhiResult { +func (c *Client) TxChOngZhi(ctx context.Context, notMustParams ...gorequest.Params) *TxChOngZhiResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 签名 c.signStr = fmt.Sprintf("userid%vpwd%vorderid%vaccount%vproductid%vamount%vip%vtimes%v", c.getUserId(), c.getPwd(), params["orderid"], params["account"], params["productid"], params["amount"], params["ip"], params["times"]) // 请求 - request, err := c.request(apiUrl+"/txchongzhi.do", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/txchongzhi.do", params, http.MethodGet) // 定义 var response TxChOngZhiResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/feishu/request.go b/service/feishu/request.go index fe8f565e..c2b89358 100644 --- a/service/feishu/request.go +++ b/service/feishu/request.go @@ -1,8 +1,12 @@ package feishu -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}) (gorequest.Response, error) { // 创建请求 client := c.client @@ -17,17 +21,17 @@ func (c *Client) request(url string, params map[string]interface{}) (gorequest.R client.SetParams(params) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/feishu/webhook.go b/service/feishu/webhook.go index 91b920fc..b2109f39 100644 --- a/service/feishu/webhook.go +++ b/service/feishu/webhook.go @@ -1,6 +1,7 @@ package feishu import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newWebhookSendResult(result WebhookSendResponse, body []byte, http goreques } // WebhookSend https://open.feishu.cn/document/ukTMukTMukTM/ucTM5YjL3ETO24yNxkjN -func (c *Client) WebhookSend(notMustParams ...gorequest.Params) *WebhookSendResult { +func (c *Client) WebhookSend(ctx context.Context, notMustParams ...gorequest.Params) *WebhookSendResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/open-apis/bot/v2/hook/%s", c.config.Key), params) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/open-apis/bot/v2/hook/%s", c.config.Key), params) // 定义 var response WebhookSendResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/jd/jd.union.open.activity.query.go b/service/jd/jd.union.open.activity.query.go index 7b5c63d5..18c1a802 100644 --- a/service/jd/jd.union.open.activity.query.go +++ b/service/jd/jd.union.open.activity.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -61,11 +62,11 @@ func newUnionOpenActivityQueryResult(responce UnionOpenActivityQueryResultRespon // UnionOpenActivityQuery 活动查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.activity.query -func (c *Client) UnionOpenActivityQuery(notMustParams ...Params) *UnionOpenActivityQueryResult { +func (c *Client) UnionOpenActivityQuery(ctx context.Context, notMustParams ...Params) *UnionOpenActivityQueryResult { // 参数 params := NewParamsWithType("jd.union.open.activity.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenActivityQueryResultResponse var result UnionOpenActivityQueryQueryResult diff --git a/service/jd/jd.union.open.category.goods.get.go b/service/jd/jd.union.open.category.goods.get.go index fb4985dd..1c24fd97 100644 --- a/service/jd/jd.union.open.category.goods.get.go +++ b/service/jd/jd.union.open.category.goods.get.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -38,11 +39,11 @@ func newUnionOpenCategoryGoodsGetResult(responce UnionOpenCategoryGoodsGetResult // UnionOpenCategoryGoodsGet 商品类目查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.category.goods.get -func (c *Client) UnionOpenCategoryGoodsGet(notMustParams ...Params) *UnionOpenCategoryGoodsGetResult { +func (c *Client) UnionOpenCategoryGoodsGet(ctx context.Context, notMustParams ...Params) *UnionOpenCategoryGoodsGetResult { // 参数 params := NewParamsWithType("jd.union.open.category.goods.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenCategoryGoodsGetResultResponse var result UnionOpenCategoryGoodsGetQueryResult diff --git a/service/jd/jd.union.open.goods.bigfield.query.go b/service/jd/jd.union.open.goods.bigfield.query.go index ccf01d1f..98b82106 100644 --- a/service/jd/jd.union.open.goods.bigfield.query.go +++ b/service/jd/jd.union.open.goods.bigfield.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -58,11 +59,11 @@ func newUnionOpenGoodsBigfieldQueryResult(responce UnionOpenGoodsBigfieldQueryRe // UnionOpenGoodsBigfieldQuery 商品详情查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.goods.bigfield.query -func (c *Client) UnionOpenGoodsBigfieldQuery(notMustParams ...Params) *UnionOpenGoodsBigfieldQueryResult { +func (c *Client) UnionOpenGoodsBigfieldQuery(ctx context.Context, notMustParams ...Params) *UnionOpenGoodsBigfieldQueryResult { // 参数 params := NewParamsWithType("jd.union.open.goods.bigfield.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenGoodsBigfieldQueryResultResponse var result UnionOpenGoodsBigfieldQueryQueryResult diff --git a/service/jd/jd.union.open.goods.jingfen.query.go b/service/jd/jd.union.open.goods.jingfen.query.go index 8ea58d14..dd8fef36 100644 --- a/service/jd/jd.union.open.goods.jingfen.query.go +++ b/service/jd/jd.union.open.goods.jingfen.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -122,11 +123,11 @@ func newUnionOpenGoodsJIngFenQueryResult(responce UnionOpenGoodsJIngFenQueryResu // UnionOpenGoodsJIngFenQuery 京粉精选商品查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.goods.jingfen.query -func (c *Client) UnionOpenGoodsJIngFenQuery(notMustParams ...Params) *UnionOpenGoodsJIngFenQueryResult { +func (c *Client) UnionOpenGoodsJIngFenQuery(ctx context.Context, notMustParams ...Params) *UnionOpenGoodsJIngFenQueryResult { // 参数 params := NewParamsWithType("jd.union.open.goods.jingfen.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenGoodsJIngFenQueryResultResponse var result UnionOpenGoodsJIngFenQueryQueryResult diff --git a/service/jd/jd.union.open.goods.material.query.go b/service/jd/jd.union.open.goods.material.query.go index 43561034..3b74f3dd 100644 --- a/service/jd/jd.union.open.goods.material.query.go +++ b/service/jd/jd.union.open.goods.material.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -119,11 +120,11 @@ func newUnionOpenGoodsMaterialQueryResult(responce UnionOpenGoodsMaterialQueryRe // UnionOpenGoodsMaterialQuery 猜你喜欢商品推荐 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.goods.material.query -func (c *Client) UnionOpenGoodsMaterialQuery(notMustParams ...Params) *UnionOpenGoodsMaterialQueryResult { +func (c *Client) UnionOpenGoodsMaterialQuery(ctx context.Context, notMustParams ...Params) *UnionOpenGoodsMaterialQueryResult { // 参数 params := NewParamsWithType("jd.union.open.goods.material.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenGoodsMaterialQueryResultResponse var result UnionOpenGoodsMaterialQueryQueryResult diff --git a/service/jd/jd.union.open.goods.promotiongoodsinfo.query.go b/service/jd/jd.union.open.goods.promotiongoodsinfo.query.go index 510d9b57..2a35cfba 100644 --- a/service/jd/jd.union.open.goods.promotiongoodsinfo.query.go +++ b/service/jd/jd.union.open.goods.promotiongoodsinfo.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -57,11 +58,11 @@ func newUnionOpenGoodsPromotionGoodsInfoQueryResult(responce UnionOpenGoodsPromo // UnionOpenGoodsPromotionGoodsInfoQuery 根据skuid查询商品信息接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.goods.promotiongoodsinfo.query -func (c *Client) UnionOpenGoodsPromotionGoodsInfoQuery(notMustParams ...Params) *UnionOpenGoodsPromotionGoodsInfoQueryResult { +func (c *Client) UnionOpenGoodsPromotionGoodsInfoQuery(ctx context.Context, notMustParams ...Params) *UnionOpenGoodsPromotionGoodsInfoQueryResult { // 参数 params := NewParamsWithType("jd.union.open.goods.promotiongoodsinfo.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenGoodsPromotionGoodsInfoQueryResultResponse var result UnionOpenGoodsPromotionGoodsInfoQueryQueryResult diff --git a/service/jd/jd.union.open.order.query.go b/service/jd/jd.union.open.order.query.go index 6d2058a8..1ef88516 100644 --- a/service/jd/jd.union.open.order.query.go +++ b/service/jd/jd.union.open.order.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -82,11 +83,11 @@ func newUnionOpenOrderQueryResult(responce UnionOpenOrderQueryResultResponse, re // UnionOpenOrderQuery 订单查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.order.query -func (c *Client) UnionOpenOrderQuery(notMustParams ...Params) *UnionOpenOrderQueryResult { +func (c *Client) UnionOpenOrderQuery(ctx context.Context, notMustParams ...Params) *UnionOpenOrderQueryResult { // 参数 params := NewParamsWithType("jd.union.open.order.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenOrderQueryResultResponse var result UnionOpenOrderQueryQueryResult diff --git a/service/jd/jd.union.open.order.row.query.go b/service/jd/jd.union.open.order.row.query.go index 650a0612..ec4f46c8 100644 --- a/service/jd/jd.union.open.order.row.query.go +++ b/service/jd/jd.union.open.order.row.query.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -91,11 +92,11 @@ func newUnionOpenOrderRowQueryResult(responce UnionOpenOrderRowQueryResultRespon // UnionOpenOrderRowQuery 订单行查询接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.order.row.query -func (c *Client) UnionOpenOrderRowQuery(notMustParams ...Params) *UnionOpenOrderRowQueryResult { +func (c *Client) UnionOpenOrderRowQuery(ctx context.Context, notMustParams ...Params) *UnionOpenOrderRowQueryResult { // 参数 params := NewParamsWithType("jd.union.open.order.row.query", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenOrderRowQueryResultResponse var result UnionOpenOrderRowQueryQueryResult diff --git a/service/jd/jd.union.open.promotion.bysubunionid.get.go b/service/jd/jd.union.open.promotion.bysubunionid.get.go index e1af25ce..2d6aeb7b 100644 --- a/service/jd/jd.union.open.promotion.bysubunionid.get.go +++ b/service/jd/jd.union.open.promotion.bysubunionid.get.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -36,11 +37,11 @@ func newUnionOpenPromotionBySubUnionIdGetResult(responce UnionOpenPromotionBySub // UnionOpenPromotionBySubUnionIdGet 社交媒体获取推广链接接口【申请】 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.promotion.bysubunionid.get -func (c *Client) UnionOpenPromotionBySubUnionIdGet(notMustParams ...Params) *UnionOpenPromotionBySubUnionIdGetResult { +func (c *Client) UnionOpenPromotionBySubUnionIdGet(ctx context.Context, notMustParams ...Params) *UnionOpenPromotionBySubUnionIdGetResult { // 参数 params := NewParamsWithType("jd.union.open.promotion.bysubunionid.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenPromotionBySubUnionIdGetResultResponse var result UnionOpenPromotionBySubUnionIdGetGetResult diff --git a/service/jd/jd.union.open.promotion.common.get.go b/service/jd/jd.union.open.promotion.common.get.go index 4f18d783..0d70627e 100644 --- a/service/jd/jd.union.open.promotion.common.get.go +++ b/service/jd/jd.union.open.promotion.common.get.go @@ -1,6 +1,7 @@ package jd import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -36,11 +37,11 @@ func newUnionOpenPromotionCommonGetResult(responce UnionOpenPromotionCommonGetRe // UnionOpenPromotionCommonGet 网站/APP获取推广链接接口 // https://union.jd.com/openplatform/api/v2?apiName=jd.union.open.promotion.common.get -func (c *Client) UnionOpenPromotionCommonGet(notMustParams ...Params) *UnionOpenPromotionCommonGetResult { +func (c *Client) UnionOpenPromotionCommonGet(ctx context.Context, notMustParams ...Params) *UnionOpenPromotionCommonGetResult { // 参数 params := NewParamsWithType("jd.union.open.promotion.common.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var responce UnionOpenPromotionCommonGetResultResponse var result UnionOpenPromotionCommonGetGetResult diff --git a/service/jd/request.go b/service/jd/request.go index 7b516a82..b98c692e 100644 --- a/service/jd/request.go +++ b/service/jd/request.go @@ -1,12 +1,14 @@ package jd import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gostring" ) // 请求接口 -func (c *Client) request(params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, params map[string]interface{}) (gorequest.Response, error) { // 签名 c.Sign(params) @@ -21,17 +23,17 @@ func (c *Client) request(params map[string]interface{}) (gorequest.Response, err client.SetParams(params) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddlewareCustom(gostring.ToString(params["method"]), request) + go c.log.GormMiddlewareCustom(ctx, gostring.ToString(params["method"]), request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddlewareCustom(gostring.ToString(params["method"]), request) + go c.log.MongoMiddlewareCustom(ctx, gostring.ToString(params["method"]), request, go_library.Version()) } return request, err diff --git a/service/kashangwl/api.buy.go b/service/kashangwl/api.buy.go index c0e7135d..b8d0bfa6 100644 --- a/service/kashangwl/api.buy.go +++ b/service/kashangwl/api.buy.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -17,11 +18,11 @@ type ApiBuyResponse struct { Cards []struct { CardNo string `json:"card_no"` CardPassword string `json:"card_password"` - } `json:"cards,omitempty"` // 卡密(仅当订单成功并且商品类型为卡密时返回此数据) + } `json:"cards,omitempty"` // 卡密(仅当订单成功并且商品类型为卡密时返回此数据) Tickets []struct { No string `json:"no"` Ticket string `json:"ticket"` - } `json:"tickets,omitempty"` // 卡券(仅当订单成功并且商品类型为卡券时返回此数据) + } `json:"tickets,omitempty"` // 卡券(仅当订单成功并且商品类型为卡券时返回此数据) } `json:"data"` } @@ -38,11 +39,11 @@ func newApiBuyResult(result ApiBuyResponse, body []byte, http gorequest.Response // ApiBuy 购买商品 // http://doc.cqmeihu.cn/sales/buy.html -func (c *Client) ApiBuy(notMustParams ...gorequest.Params) *ApiBuyResult { +func (c *Client) ApiBuy(ctx context.Context, notMustParams ...gorequest.Params) *ApiBuyResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/api/buy", params) + request, err := c.request(ctx, apiUrl+"/api/buy", params) // 定义 var response ApiBuyResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/api.customer.go b/service/kashangwl/api.customer.go index 908a870b..b7462f8a 100644 --- a/service/kashangwl/api.customer.go +++ b/service/kashangwl/api.customer.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -28,9 +29,9 @@ func newApiCustomerResult(result ApiCustomerResponse, body []byte, http goreques // ApiCustomer 获取商家信息 // http://doc.cqmeihu.cn/sales/merchant-info.html -func (c *Client) ApiCustomer() *ApiCustomerResult { +func (c *Client) ApiCustomer(ctx context.Context) *ApiCustomerResult { // 请求 - request, err := c.request(apiUrl+"/api/customer", map[string]interface{}{}) + request, err := c.request(ctx, apiUrl+"/api/customer", map[string]interface{}{}) // 定义 var response ApiCustomerResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/api.order.go b/service/kashangwl/api.order.go index 5829f458..35f728b4 100644 --- a/service/kashangwl/api.order.go +++ b/service/kashangwl/api.order.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -52,13 +53,13 @@ func newApiOrderResult(result ApiOrderResponse, body []byte, http gorequest.Resp // ApiOrder 获取单个订单信息。 // 仅能获取自己购买的订单。 // http://doc.cqmeihu.cn/sales/order-info.html -func (c *Client) ApiOrder(orderId string) *ApiOrderResult { +func (c *Client) ApiOrder(ctx context.Context, orderId string) *ApiOrderResult { // 参数 param := gorequest.NewParams() param.Set("order_id", orderId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/api/order", params) + request, err := c.request(ctx, apiUrl+"/api/order", params) // 定义 var response ApiOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/api.outer-order.go b/service/kashangwl/api.outer-order.go index f4105785..e73d5b67 100644 --- a/service/kashangwl/api.outer-order.go +++ b/service/kashangwl/api.outer-order.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -52,13 +53,13 @@ func newApiOuterOrderResult(result ApiOuterOrderResponse, body []byte, http gore // ApiOuterOrder 使用外部订单号获取单个订单信息 // 仅能获取自己购买的订单 // http://doc.cqmeihu.cn/sales/outer-order-info.html -func (c *Client) ApiOuterOrder(orderId string) *ApiOuterOrderResult { +func (c *Client) ApiOuterOrder(ctx context.Context, orderId string) *ApiOuterOrderResult { // 参数 param := gorequest.NewParams() param.Set("outer_order_id", orderId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/api/outer-order", params) + request, err := c.request(ctx, apiUrl+"/api/outer-order", params) // 定义 var response ApiOuterOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/api.product.cache.go b/service/kashangwl/api.product.cache.go new file mode 100644 index 00000000..dddab400 --- /dev/null +++ b/service/kashangwl/api.product.cache.go @@ -0,0 +1,47 @@ +package kashangwl + +import ( + "context" + "encoding/json" + "fmt" + "github.com/dtapps/go-library/utils/gorequest" + "net/http" +) + +type ApiProductCacheResponse struct { + Code int `json:"code"` + Message string `json:"message"` + Data struct { + GoodsId string `json:"goods_id"` + ApiGoodsId int `json:"api_goods_id"` + GoodsName string `json:"goods_name"` + ClassificationName string `json:"classification_name"` + GoodsPrice float64 `json:"goods_price"` + PurchaseTips string `json:"purchase_tips"` + } `json:"data"` + Time int `json:"time"` + TraceId string `json:"trace_id"` +} + +type ApiProductCacheResult struct { + Result ApiProductCacheResponse // 结果 + Body []byte // 内容 + Http gorequest.Response // 请求 + Err error // 错误 +} + +func newApiProductCacheResult(result ApiProductCacheResponse, body []byte, http gorequest.Response, err error) *ApiProductCacheResult { + return &ApiProductCacheResult{Result: result, Body: body, Http: http, Err: err} +} + +// ApiProductCache [缓存,需托管授权]获取单个商品信息 +func (c *Client) ApiProductCache(ctx context.Context, productId int64) *ApiProductCacheResult { + // 参数 + params := gorequest.NewParams() + // 请求 + request, err := c.requestCache(ctx, fmt.Sprintf("%s/%d/goods_info/%d", apiUrlCache, c.GetCustomerId(), productId), params, http.MethodGet) + // 定义 + var response ApiProductCacheResponse + err = json.Unmarshal(request.ResponseBody, &response) + return newApiProductCacheResult(response, request.ResponseBody, request, err) +} diff --git a/service/kashangwl/api.product.go b/service/kashangwl/api.product.go index 117338d9..f1b360de 100644 --- a/service/kashangwl/api.product.go +++ b/service/kashangwl/api.product.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -17,7 +18,7 @@ type ApiProductResponse struct { SuperiorCommissionsRate int `json:"superior_commissions_rate"` // 上级佣金比例 Type int `json:"type"` // 商品类型(1:充值,2:卡密,3:卡券,4:人工) SupplyState int `json:"supply_state"` // 库存状态(1:充足,2:断货) - StockState int `json:"stock_state"` // 状态(1:上架,2:维护,3:下架) + StockState int `json:"stock_state"` // 状态(1:上架,2:维护,3:下架) BanStartAt string `json:"ban_start_at"` // 禁售开始时间 BanEndAt string `json:"ban_end_at"` // 禁售结束时间 } `json:"data"` @@ -36,12 +37,12 @@ func newApiProductResult(result ApiProductResponse, body []byte, http gorequest. // ApiProduct 获取单个商品信息 // http://doc.cqmeihu.cn/sales/product-info.html -func (c *Client) ApiProduct(productId int64) *ApiProductResult { +func (c *Client) ApiProduct(ctx context.Context, productId int64) *ApiProductResult { // 参数 params := gorequest.NewParams() params.Set("product_id", productId) // 请求 - request, err := c.request(apiUrl+"/api/product", params) + request, err := c.request(ctx, apiUrl+"/api/product", params) // 定义 var response ApiProductResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/api.product.recharge-params.go b/service/kashangwl/api.product.recharge-params.go index 0269024b..3da5a1f1 100644 --- a/service/kashangwl/api.product.recharge-params.go +++ b/service/kashangwl/api.product.recharge-params.go @@ -1,6 +1,7 @@ package kashangwl import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -32,12 +33,12 @@ func newApiProductRechargeParamsResult(result ApiProductRechargeParamsResponse, // ApiProductRechargeParams 接口说明 // 获取商品的充值参数(仅支持充值类商品) // http://doc.cqmeihu.cn/sales/ProductParams.html -func (c *Client) ApiProductRechargeParams(productId int64) *ApiProductRechargeParamsResult { +func (c *Client) ApiProductRechargeParams(ctx context.Context, productId int64) *ApiProductRechargeParamsResult { // 参数 params := gorequest.NewParams() params.Set("product_id", productId) // 请求 - request, err := c.request(apiUrl+"/api/product/recharge-params", params) + request, err := c.request(ctx, apiUrl+"/api/product/recharge-params", params) // 定义 var response ApiProductRechargeParamsResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/kashangwl/const.go b/service/kashangwl/const.go index 1a47a930..e3e13be8 100644 --- a/service/kashangwl/const.go +++ b/service/kashangwl/const.go @@ -5,7 +5,12 @@ const ( ) const ( - apiUrl = "http://www.kashangwl.com" + CodeCacheSuccess = 1 +) + +const ( + apiUrl = "http://www.kashangwl.com" + apiUrlCache = "https://api.dtapp.net/v1/866ka" ) const ( diff --git a/service/kashangwl/request.go b/service/kashangwl/request.go index 405802ea..5e400954 100644 --- a/service/kashangwl/request.go +++ b/service/kashangwl/request.go @@ -1,11 +1,13 @@ package kashangwl import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "time" ) -func (c *Client) request(url string, params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}) (gorequest.Response, error) { // 公共参数 params["timestamp"] = time.Now().UnixNano() / 1e6 @@ -27,17 +29,51 @@ func (c *Client) request(url string, params map[string]interface{}) (gorequest.R client.SetParams(params) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) + } + + return request, err +} + +func (c *Client) requestCache(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { + + // 创建请求 + client := c.client + + // 设置请求地址 + client.SetUri(url) + + // 设置方式 + client.SetMethod(method) + + // 设置FORM格式 + client.SetContentTypeJson() + + // 设置参数 + client.SetParams(params) + + // 发起请求 + request, err := client.Request(ctx) + if err != nil { + return gorequest.Response{}, err + } + + // 日志 + if c.config.PgsqlDb != nil { + go c.log.GormMiddleware(ctx, request, go_library.Version()) + } + if c.config.MongoDb != nil { + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/kuaishou/api.go b/service/kuaishou/api.go index 35b020c1..4a0c4212 100644 --- a/service/kuaishou/api.go +++ b/service/kuaishou/api.go @@ -1,6 +1,7 @@ package kuaishou import ( + "context" "errors" "github.com/mvdan/xurls" "strings" @@ -21,7 +22,7 @@ func newAnalysisResult(result AnalysisResponse, err error) *AnalysisResult { } // Analysis 快手解析 -func (c *Client) Analysis(content string) *AnalysisResult { +func (c *Client) Analysis(ctx context.Context, content string) *AnalysisResult { // 定义 var response AnalysisResponse diff --git a/service/meituan/api.generate_link.go b/service/meituan/api.generate_link.go index c8d79232..73b42a98 100644 --- a/service/meituan/api.generate_link.go +++ b/service/meituan/api.generate_link.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -25,7 +26,7 @@ func newApiGenerateLinkResult(result ApiGenerateLinkResponse, body []byte, http // ApiGenerateLink 自助取链接口(新版) // https://union.meituan.com/v2/apiDetail?id=25 -func (c *Client) ApiGenerateLink(actId int64, sid string, linkType, shortLink int) *ApiGenerateLinkResult { +func (c *Client) ApiGenerateLink(ctx context.Context, actId int64, sid string, linkType, shortLink int) *ApiGenerateLinkResult { // 参数 param := gorequest.NewParams() param.Set("actId", actId) // 活动id,可以在联盟活动列表中查看获取 @@ -37,7 +38,7 @@ func (c *Client) ApiGenerateLink(actId int64, sid string, linkType, shortLink in params := gorequest.NewParamsWith(param) params["sign"] = c.getSign(c.config.Secret, params) // 请求 - request, err := c.request(apiUrl+"/api/generateLink", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/api/generateLink", params, http.MethodGet) // 定义 var response ApiGenerateLinkResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/api.getqualityscorebysid.go b/service/meituan/api.getqualityscorebysid.go index df655dbe..595bafc5 100644 --- a/service/meituan/api.getqualityscorebysid.go +++ b/service/meituan/api.getqualityscorebysid.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gotime" @@ -34,7 +35,7 @@ func newApiGetQuaLitYsCoreBySidResult(result ApiGetQuaLitYsCoreBySidResponse, bo // ApiGetQuaLitYsCoreBySid 优选sid质量分&复购率查询 // https://union.meituan.com/v2/apiDetail?id=28 -func (c *Client) ApiGetQuaLitYsCoreBySid(notMustParams ...gorequest.Params) *ApiGetQuaLitYsCoreBySidResult { +func (c *Client) ApiGetQuaLitYsCoreBySid(ctx context.Context, notMustParams ...gorequest.Params) *ApiGetQuaLitYsCoreBySidResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求时刻10位时间戳(秒级),有效期60s @@ -42,7 +43,7 @@ func (c *Client) ApiGetQuaLitYsCoreBySid(notMustParams ...gorequest.Params) *Api params["appkey"] = c.config.AppKey params["sign"] = c.getSign(c.config.Secret, params) // 请求 - request, err := c.request(apiUrl+"/api/getqualityscorebysid", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/api/getqualityscorebysid", params, http.MethodGet) // 定义 var response ApiGetQuaLitYsCoreBySidResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/api.mini_code.go b/service/meituan/api.mini_code.go index 5d2d894c..97a011bd 100644 --- a/service/meituan/api.mini_code.go +++ b/service/meituan/api.mini_code.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -25,7 +26,7 @@ func newApiMiniCodeResult(result ApiMiniCodeResponse, body []byte, http goreques // ApiMiniCode 小程序生成二维码(新版) // https://union.meituan.com/v2/apiDetail?id=26 -func (c *Client) ApiMiniCode(actId int64, sid string) *ApiMiniCodeResult { +func (c *Client) ApiMiniCode(ctx context.Context, actId int64, sid string) *ApiMiniCodeResult { // 参数 param := gorequest.NewParams() param.Set("appkey", c.config.AppKey) @@ -35,7 +36,7 @@ func (c *Client) ApiMiniCode(actId int64, sid string) *ApiMiniCodeResult { params := gorequest.NewParamsWith(param) params["sign"] = c.getSign(c.config.Secret, params) // 请求 - request, err := c.request(apiUrl+"/api/miniCode", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/api/miniCode", params, http.MethodGet) // 定义 var response ApiMiniCodeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/api.order.go b/service/meituan/api.order.go index 63fd4d31..3850784e 100644 --- a/service/meituan/api.order.go +++ b/service/meituan/api.order.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -47,14 +48,14 @@ func newApiOrderResult(result ApiOrderResponse, body []byte, http gorequest.Resp // ApiOrder 单订单查询接口(新版) // https://union.meituan.com/v2/apiDetail?id=24 -func (c *Client) ApiOrder(notMustParams ...gorequest.Params) *ApiOrderResult { +func (c *Client) ApiOrder(ctx context.Context, notMustParams ...gorequest.Params) *ApiOrderResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求时刻10位时间戳(秒级),有效期60s params["appkey"] = c.config.AppKey params["sign"] = c.getSign(c.config.Secret, params) // 请求 - request, err := c.request(apiUrl+"/api/order", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/api/order", params, http.MethodGet) // 定义 var response ApiOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/api.order_list.go b/service/meituan/api.order_list.go index 7a71b6d3..e4ff1a58 100644 --- a/service/meituan/api.order_list.go +++ b/service/meituan/api.order_list.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gotime" @@ -46,7 +47,7 @@ func newApiOrderListResult(result ApiOrderListResponse, body []byte, http gorequ // ApiOrderList 订单列表查询接口(新版) // https://union.meituan.com/v2/apiDetail?id=23 -func (c *Client) ApiOrderList(notMustParams ...gorequest.Params) *ApiOrderListResult { +func (c *Client) ApiOrderList(ctx context.Context, notMustParams ...gorequest.Params) *ApiOrderListResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求时刻10位时间戳(秒级),有效期60s @@ -54,7 +55,7 @@ func (c *Client) ApiOrderList(notMustParams ...gorequest.Params) *ApiOrderListRe params["appkey"] = c.config.AppKey params["sign"] = c.getSign(c.config.Secret, params) // 请求 - request, err := c.request(apiUrl+"/api/orderList", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/api/orderList", params, http.MethodGet) // 定义 var response ApiOrderListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/poi.area.go b/service/meituan/poi.area.go index 165833bb..40d46098 100644 --- a/service/meituan/poi.area.go +++ b/service/meituan/poi.area.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -31,13 +32,13 @@ func newPoiAreaResult(result PoiAreaResponse, body []byte, http gorequest.Respon // PoiArea 基础数据 - 商圈接口 // https://openapi.meituan.com/#api-0.%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE-GetHttpsOpenapiMeituanComPoiAreaCityid1 -func (c *Client) PoiArea(cityID int) *PoiAreaResult { +func (c *Client) PoiArea(ctx context.Context, cityID int) *PoiAreaResult { // 参数 param := gorequest.NewParams() param.Set("cityid", cityID) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/poi/area", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/poi/area", params, http.MethodGet) // 定义 var response PoiAreaResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/poi.category.go b/service/meituan/poi.category.go index bf9e860c..a3dad935 100644 --- a/service/meituan/poi.category.go +++ b/service/meituan/poi.category.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -31,13 +32,13 @@ func newPoiCategoryResult(result PoiCategoryResponse, body []byte, http goreques // PoiCategory 基础数据 - 品类接口 // https://openapi.meituan.com/#api-0.%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE-GetHttpsOpenapiMeituanComPoiDistrictCityid1 -func (c *Client) PoiCategory(cityID int) *PoiCategoryResult { +func (c *Client) PoiCategory(ctx context.Context, cityID int) *PoiCategoryResult { // 参数 param := gorequest.NewParams() param.Set("cityid", cityID) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/poi/category", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/poi/category", params, http.MethodGet) // 定义 var response PoiCategoryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/poi.city.go b/service/meituan/poi.city.go index cf559360..1f9794be 100644 --- a/service/meituan/poi.city.go +++ b/service/meituan/poi.city.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -28,9 +29,9 @@ func newPoiCityResult(result PoiCityResponse, body []byte, http gorequest.Respon // PoiCity 基础数据 - 开放城市接口 // https://openapi.meituan.com/#api-0.%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE-GetHttpsOpenapiMeituanComPoiCity -func (c *Client) PoiCity() *PoiCityResult { +func (c *Client) PoiCity(ctx context.Context) *PoiCityResult { // 请求 - request, err := c.request(apiUrl+"/poi/city", map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/poi/city", map[string]interface{}{}, http.MethodGet) // 定义 var response PoiCityResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/poi.district.go b/service/meituan/poi.district.go index 8aa1ce16..eb78c5de 100644 --- a/service/meituan/poi.district.go +++ b/service/meituan/poi.district.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -27,13 +28,13 @@ func newPoiDistrictResult(result PoiDistrictResponse, body []byte, http goreques // PoiDistrict 基础数据 - 城市的行政区接口 // https://openapi.meituan.com/#api-0.%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE-GetHttpsOpenapiMeituanComPoiDistrictCityid1 -func (c *Client) PoiDistrict(cityID int) *PoiDistrictResult { +func (c *Client) PoiDistrict(ctx context.Context, cityID int) *PoiDistrictResult { // 参数 param := gorequest.NewParams() param.Set("cityid", cityID) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/poi/district", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/poi/district", params, http.MethodGet) // 定义 var response PoiDistrictResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/meituan/request.go b/service/meituan/request.go index de1cf0a4..c8f79f25 100644 --- a/service/meituan/request.go +++ b/service/meituan/request.go @@ -1,8 +1,12 @@ package meituan -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -20,17 +24,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/meituan/service_http.order.go b/service/meituan/service_http.order.go index a3b36e5e..055f700c 100644 --- a/service/meituan/service_http.order.go +++ b/service/meituan/service_http.order.go @@ -1,6 +1,7 @@ package meituan import ( + "context" "github.com/gin-gonic/gin" "net/http" ) @@ -37,7 +38,7 @@ type ResponseServeHttpOrder struct { // ServeHttpOrder 订单回推接口(新版) // https://union.meituan.com/v2/apiDetail?id=22 -func (c *Client) ServeHttpOrder(gCtx *gin.Context) (validateJson ResponseServeHttpOrder, err error) { +func (c *Client) ServeHttpOrder(ctx context.Context, gCtx *gin.Context) (validateJson ResponseServeHttpOrder, err error) { // 声明接收的变量 err = gCtx.ShouldBind(&validateJson) return diff --git a/service/pinduoduo/pdd.ddk.cms.prom.url.generate.go b/service/pinduoduo/pdd.ddk.cms.prom.url.generate.go index a2b48c79..a0552761 100644 --- a/service/pinduoduo/pdd.ddk.cms.prom.url.generate.go +++ b/service/pinduoduo/pdd.ddk.cms.prom.url.generate.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -62,12 +63,12 @@ func newCmsPromUrlGenerateResult(result CmsPromUrlGenerateResponse, body []byte, // CmsPromUrlGenerate 生成商城-频道推广链接 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.cms.prom.url.generate -func (c *Client) CmsPromUrlGenerate(notMustParams ...Params) *CmsPromUrlGenerateResult { +func (c *Client) CmsPromUrlGenerate(ctx context.Context, notMustParams ...Params) *CmsPromUrlGenerateResult { // 参数 params := NewParamsWithType("pdd.ddk.cms.prom.url.generate", notMustParams...) params.Set("p_id_list", []string{c.config.Pid}) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response CmsPromUrlGenerateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.goods.detail.go b/service/pinduoduo/pdd.ddk.goods.detail.go index 95a4faa5..ddbb0b76 100644 --- a/service/pinduoduo/pdd.ddk.goods.detail.go +++ b/service/pinduoduo/pdd.ddk.goods.detail.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -97,12 +98,12 @@ func newGoodsDetailResult(result GoodsDetailResponse, body []byte, http goreques // GoodsDetail 多多进宝商品详情查询 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.detail -func (c *Client) GoodsDetail(notMustParams ...Params) *GoodsDetailResult { +func (c *Client) GoodsDetail(ctx context.Context, notMustParams ...Params) *GoodsDetailResult { // 参数 params := NewParamsWithType("pdd.ddk.goods.detail", notMustParams...) params.Set("pid", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsDetailResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.goods.pid.generate.go b/service/pinduoduo/pdd.ddk.goods.pid.generate.go index 1fe33e79..dc6dcc5b 100644 --- a/service/pinduoduo/pdd.ddk.goods.pid.generate.go +++ b/service/pinduoduo/pdd.ddk.goods.pid.generate.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -30,11 +31,11 @@ func newGoodsPidGenerateResult(result GoodsPidGenerateResponse, body []byte, htt // GoodsPidGenerate 创建多多进宝推广位 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.pid.generate -func (c *Client) GoodsPidGenerate(notMustParams ...Params) *GoodsPidGenerateResult { +func (c *Client) GoodsPidGenerate(ctx context.Context, notMustParams ...Params) *GoodsPidGenerateResult { // 参数 params := NewParamsWithType("pdd.ddk.goods.pid.generate", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsPidGenerateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.goods.promotion.url.generate.go b/service/pinduoduo/pdd.ddk.goods.promotion.url.generate.go index fa5438ee..c2cccccf 100644 --- a/service/pinduoduo/pdd.ddk.goods.promotion.url.generate.go +++ b/service/pinduoduo/pdd.ddk.goods.promotion.url.generate.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -50,12 +51,12 @@ func newGoodsPromotionUrlGenerateResult(result GoodsPromotionUrlGenerateResponse // GoodsPromotionUrlGenerate 多多进宝推广链接生成 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.promotion.url.generate -func (c *Client) GoodsPromotionUrlGenerate(notMustParams ...Params) *GoodsPromotionUrlGenerateResult { +func (c *Client) GoodsPromotionUrlGenerate(ctx context.Context, notMustParams ...Params) *GoodsPromotionUrlGenerateResult { // 参数 params := NewParamsWithType("pdd.ddk.goods.promotion.url.generate", notMustParams...) params.Set("p_id", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsPromotionUrlGenerateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.goods.recommend.get.go b/service/pinduoduo/pdd.ddk.goods.recommend.get.go index aee0972b..938a9fb0 100644 --- a/service/pinduoduo/pdd.ddk.goods.recommend.get.go +++ b/service/pinduoduo/pdd.ddk.goods.recommend.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -79,12 +80,12 @@ func newGoodsRecommendGetResult(result GoodsRecommendGetResponse, body []byte, h // GoodsRecommendGet 多多进宝商品推荐API // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.recommend.get -func (c *Client) GoodsRecommendGet(notMustParams ...Params) *GoodsRecommendGetResult { +func (c *Client) GoodsRecommendGet(ctx context.Context, notMustParams ...Params) *GoodsRecommendGetResult { // 参数 params := NewParamsWithType("pdd.ddk.goods.recommend.get", notMustParams...) params.Set("pid", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsRecommendGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.goods.search.go b/service/pinduoduo/pdd.ddk.goods.search.go index 54887d78..67d54a74 100644 --- a/service/pinduoduo/pdd.ddk.goods.search.go +++ b/service/pinduoduo/pdd.ddk.goods.search.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -93,12 +94,12 @@ func newGoodsSearchResult(result GoodsSearchResponse, body []byte, http goreques // GoodsSearch 多多进宝商品查询 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.search -func (c *Client) GoodsSearch(notMustParams ...Params) *GoodsSearchResult { +func (c *Client) GoodsSearch(ctx context.Context, notMustParams ...Params) *GoodsSearchResult { // 参数 params := NewParamsWithType("pdd.ddk.goods.search", notMustParams...) params.Set("pid", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsSearchResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.member.authority.query.go b/service/pinduoduo/pdd.ddk.member.authority.query.go index 0923a31e..805f2d62 100644 --- a/service/pinduoduo/pdd.ddk.member.authority.query.go +++ b/service/pinduoduo/pdd.ddk.member.authority.query.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -25,12 +26,12 @@ func newMemberAuthorityQueryResult(result MemberAuthorityQueryResponse, body []b // MemberAuthorityQuery 查询是否绑定备案 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.search -func (c *Client) MemberAuthorityQuery(notMustParams ...Params) *MemberAuthorityQueryResult { +func (c *Client) MemberAuthorityQuery(ctx context.Context, notMustParams ...Params) *MemberAuthorityQueryResult { // 参数 params := NewParamsWithType("pdd.ddk.member.authority.query", notMustParams...) params.Set("pid", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response MemberAuthorityQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.order.detail.get.go b/service/pinduoduo/pdd.ddk.order.detail.get.go index f113f4bd..c1d9314e 100644 --- a/service/pinduoduo/pdd.ddk.order.detail.get.go +++ b/service/pinduoduo/pdd.ddk.order.detail.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -66,13 +67,13 @@ func newOrderDetailGetResult(result OrderDetailGetResponse, body []byte, http go } // OrderDetailGet 多多进宝商品查询 https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.order.detail.get -func (c *Client) OrderDetailGet(orderSn string) *OrderDetailGetResult { +func (c *Client) OrderDetailGet(ctx context.Context, orderSn string) *OrderDetailGetResult { // 参数 param := NewParams() param.Set("order_sn", orderSn) params := NewParamsWithType("pdd.ddk.order.detail.get", param) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response OrderDetailGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.order.list.increment.get.go b/service/pinduoduo/pdd.ddk.order.list.increment.get.go index 346d4f0a..1c7d5224 100644 --- a/service/pinduoduo/pdd.ddk.order.list.increment.get.go +++ b/service/pinduoduo/pdd.ddk.order.list.increment.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -71,11 +72,11 @@ func newOrderListIncrementGetResult(result OrderListIncrementGetResponse, body [ // OrderListIncrementGet 最后更新时间段增量同步推广订单信息 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.order.list.increment.get -func (c *Client) OrderListIncrementGet(notMustParams ...Params) *OrderListIncrementGetResult { +func (c *Client) OrderListIncrementGet(ctx context.Context, notMustParams ...Params) *OrderListIncrementGetResult { // 参数 params := NewParamsWithType("pdd.ddk.order.list.increment.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response OrderListIncrementGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.order.list.range.get.go b/service/pinduoduo/pdd.ddk.order.list.range.get.go index 3c8246e7..0b6f1ec9 100644 --- a/service/pinduoduo/pdd.ddk.order.list.range.get.go +++ b/service/pinduoduo/pdd.ddk.order.list.range.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -71,11 +72,11 @@ func newOrderListRangeGetResult(result OrderListRangeGetResponse, body []byte, h // OrderListRangeGet 用时间段查询推广订单接口 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.order.list.range.get -func (c *Client) OrderListRangeGet(notMustParams ...Params) *OrderListRangeGetResult { +func (c *Client) OrderListRangeGet(ctx context.Context, notMustParams ...Params) *OrderListRangeGetResult { // 参数 params := NewParamsWithType("pdd.ddk.order.list.range.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response OrderListRangeGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.resource.url.gen.go b/service/pinduoduo/pdd.ddk.resource.url.gen.go index 9583519e..224a1c89 100644 --- a/service/pinduoduo/pdd.ddk.resource.url.gen.go +++ b/service/pinduoduo/pdd.ddk.resource.url.gen.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -51,12 +52,12 @@ func newResourceUrlGenResult(result ResourceUrlGenResponse, body []byte, http go // ResourceUrlGen 生成多多进宝频道推广 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.goods.pid.generate -func (c *Client) ResourceUrlGen(notMustParams ...Params) *ResourceUrlGenResult { +func (c *Client) ResourceUrlGen(ctx context.Context, notMustParams ...Params) *ResourceUrlGenResult { // 参数 params := NewParamsWithType("pdd.ddk.resource.url.gen", notMustParams...) params.Set("pid", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response ResourceUrlGenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.rp.prom.url.generate.go b/service/pinduoduo/pdd.ddk.rp.prom.url.generate.go index 1ab7f172..0d7a099d 100644 --- a/service/pinduoduo/pdd.ddk.rp.prom.url.generate.go +++ b/service/pinduoduo/pdd.ddk.rp.prom.url.generate.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -66,12 +67,12 @@ func newRpPromUrlGenerateResult(result RpPromUrlGenerateResponse, body []byte, h // RpPromUrlGenerate 生成营销工具推广链接 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.rp.prom.url.generate -func (c *Client) RpPromUrlGenerate(notMustParams ...Params) *RpPromUrlGenerateResult { +func (c *Client) RpPromUrlGenerate(ctx context.Context, notMustParams ...Params) *RpPromUrlGenerateResult { // 参数 params := NewParamsWithType("pdd.ddk.rp.prom.url.generate", notMustParams...) params.Set("p_id_list", []string{c.config.Pid}) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response RpPromUrlGenerateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.ddk.top.goods.list.query.go b/service/pinduoduo/pdd.ddk.top.goods.list.query.go index b5339cd3..e43d83a2 100644 --- a/service/pinduoduo/pdd.ddk.top.goods.list.query.go +++ b/service/pinduoduo/pdd.ddk.top.goods.list.query.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -59,12 +60,12 @@ func newTopGoodsListQueryResult(result TopGoodsListQueryResponse, body []byte, h // TopGoodsListQuery 多多客获取爆款排行商品接口 // https://jinbao.pinduoduo.com/third-party/api-detail?apiName=pdd.ddk.top.goods.list.query -func (c *Client) TopGoodsListQuery(notMustParams ...Params) *TopGoodsListQueryResult { +func (c *Client) TopGoodsListQuery(ctx context.Context, notMustParams ...Params) *TopGoodsListQueryResult { // 参数 params := NewParamsWithType("pdd.ddk.top.goods.list.query", notMustParams...) params.Set("p_id", c.config.Pid) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TopGoodsListQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.goods.cats.get.go b/service/pinduoduo/pdd.goods.cats.get.go index e5ee1067..140fd407 100644 --- a/service/pinduoduo/pdd.goods.cats.get.go +++ b/service/pinduoduo/pdd.goods.cats.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -29,13 +30,13 @@ func newGoodsCatsGetResult(result GoodsCatsGetResponse, body []byte, http gorequ // GoodsCatsGet 商品标准类目接口 // https://open.pinduoduo.com/application/document/api?id=pdd.goods.cats.get -func (c *Client) GoodsCatsGet(parentOptId int) *GoodsCatsGetResult { +func (c *Client) GoodsCatsGet(ctx context.Context, parentOptId int) *GoodsCatsGetResult { // 参数 param := NewParams() param.Set("parent_cat_id", parentOptId) params := NewParamsWithType("pdd.goods.cats.get", param) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsCatsGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/pdd.goods.opt.get.go b/service/pinduoduo/pdd.goods.opt.get.go index ee241d77..95296217 100644 --- a/service/pinduoduo/pdd.goods.opt.get.go +++ b/service/pinduoduo/pdd.goods.opt.get.go @@ -1,6 +1,7 @@ package pinduoduo import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -29,13 +30,13 @@ func newGoodsOptGetResult(result GoodsOptGetResponse, body []byte, http goreques // GoodsOptGet 查询商品标签列表 // https://open.pinduoduo.com/application/document/api?id=pdd.goods.opt.get -func (c *Client) GoodsOptGet(parentOptId int) *GoodsOptGetResult { +func (c *Client) GoodsOptGet(ctx context.Context, parentOptId int) *GoodsOptGetResult { // 参数 param := NewParams() param.Set("parent_opt_id", parentOptId) params := NewParamsWithType("pdd.goods.opt.get", param) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response GoodsOptGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pinduoduo/request.go b/service/pinduoduo/request.go index 5430b279..b388d256 100644 --- a/service/pinduoduo/request.go +++ b/service/pinduoduo/request.go @@ -1,11 +1,13 @@ package pinduoduo import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gostring" ) -func (c *Client) request(params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, params map[string]interface{}) (gorequest.Response, error) { // 签名 c.Sign(params) @@ -17,17 +19,17 @@ func (c *Client) request(params map[string]interface{}) (gorequest.Response, err client.SetParams(params) // 发起请求 - request, err := client.Get() + request, err := client.Get(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddlewareCustom(gostring.ToString(params["type"]), request) + go c.log.GormMiddlewareCustom(ctx, gostring.ToString(params["type"]), request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddlewareCustom(gostring.ToString(params["type"]), request) + go c.log.MongoMiddlewareCustom(ctx, gostring.ToString(params["type"]), request, go_library.Version()) } return request, err diff --git a/service/pintoto/api.order.create-soon-order.go b/service/pintoto/api.order.create-soon-order.go index e25871aa..25354d90 100644 --- a/service/pintoto/api.order.create-soon-order.go +++ b/service/pintoto/api.order.create-soon-order.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -42,7 +43,7 @@ func newApiOrderCreateSoonOrderResult(result ApiOrderCreateSoonOrderResponse, bo } // ApiOrderCreateSoonOrder 秒出单下单 https://www.showdoc.com.cn/1154868044931571/6437295495912025 -func (c *Client) ApiOrderCreateSoonOrder(param ApiOrderCreateSoonOrder) *ApiOrderCreateSoonOrderResult { +func (c *Client) ApiOrderCreateSoonOrder(ctx context.Context, param ApiOrderCreateSoonOrder) *ApiOrderCreateSoonOrderResult { // api params params := map[string]interface{}{} b, _ := json.Marshal(¶m) @@ -51,7 +52,7 @@ func (c *Client) ApiOrderCreateSoonOrder(param ApiOrderCreateSoonOrder) *ApiOrde for k, v := range m { params[k] = v } - request, err := c.request(apiUrl+"/api/order/create-soon-order", params) + request, err := c.request(ctx, apiUrl+"/api/order/create-soon-order", params) // 定义 var response ApiOrderCreateSoonOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/api.order.create.go b/service/pintoto/api.order.create.go index fda3172b..6c9bf370 100644 --- a/service/pintoto/api.order.create.go +++ b/service/pintoto/api.order.create.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -23,11 +24,11 @@ func newApiOrderCreateResult(result ApiOrderCreateResponse, body []byte, http go } // ApiOrderCreate 下单api https://www.showdoc.com.cn/1154868044931571/5891022916496848 -func (c *Client) ApiOrderCreate(notMustParams ...gorequest.Params) *ApiOrderCreateResult { +func (c *Client) ApiOrderCreate(ctx context.Context, notMustParams ...gorequest.Params) *ApiOrderCreateResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/api/order/create", params) + request, err := c.request(ctx, apiUrl+"/api/order/create", params) // 定义 var response ApiOrderCreateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/api.order.query.go b/service/pintoto/api.order.query.go index 345ef9aa..5f33f4eb 100644 --- a/service/pintoto/api.order.query.go +++ b/service/pintoto/api.order.query.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -45,13 +46,13 @@ func newApiOrderQueryResult(result ApiOrderQueryResponse, body []byte, http gore } // ApiOrderQuery 订单查询 https://www.showdoc.com.cn/1154868044931571/5965244588489845 -func (c *Client) ApiOrderQuery(thirdOrderId string) *ApiOrderQueryResult { +func (c *Client) ApiOrderQuery(ctx context.Context, thirdOrderId string) *ApiOrderQueryResult { // 测试 param := gorequest.NewParams() param.Set("thirdOrderId", thirdOrderId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/api/order/query", params) + request, err := c.request(ctx, apiUrl+"/api/order/query", params) // 定义 var response ApiOrderQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/api.user.info.go b/service/pintoto/api.user.info.go index a0b0674c..7709f79a 100644 --- a/service/pintoto/api.user.info.go +++ b/service/pintoto/api.user.info.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -29,8 +30,8 @@ func newApiUserInfoResult(result ApiUserInfoResponse, body []byte, http goreques } // ApiUserInfo 账号信息查询 https://www.showdoc.com.cn/1154868044931571/6269224958928211 -func (c *Client) ApiUserInfo() *ApiUserInfoResult { - request, err := c.request(apiUrl+"/api/user/info", map[string]interface{}{}) +func (c *Client) ApiUserInfo(ctx context.Context) *ApiUserInfoResult { + request, err := c.request(ctx, apiUrl+"/api/user/info", map[string]interface{}{}) // 定义 var response ApiUserInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_cinema_list.go b/service/pintoto/movie_info_get_cinema_list.go index 650e45b6..f0e01890 100644 --- a/service/pintoto/movie_info_get_cinema_list.go +++ b/service/pintoto/movie_info_get_cinema_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -37,14 +38,14 @@ func newGetCinemaListResult(result GetCinemaListResponse, body []byte, http gore } // GetCinemaList 影院列表 https://www.showdoc.com.cn/1154868044931571/5866426126744792 -func (c *Client) GetCinemaList(cityId int) *GetCinemaListResult { +func (c *Client) GetCinemaList(ctx context.Context, cityId int) *GetCinemaListResult { // 参数 param := gorequest.NewParams() param.Set("cityId", cityId) // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-cinema-list", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-cinema-list", params) // 定义 var response GetCinemaListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_city_area.go b/service/pintoto/movie_info_get_city_area.go index a122547d..46b0a804 100644 --- a/service/pintoto/movie_info_get_city_area.go +++ b/service/pintoto/movie_info_get_city_area.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -30,13 +31,13 @@ func newGetCityAreaResult(result GetCityAreaResponse, body []byte, http goreques // GetCityArea 城市下区域 // https://www.showdoc.com.cn/1154868044931571/6243539682553126 -func (c *Client) GetCityArea(cityId int) *GetCityAreaResult { +func (c *Client) GetCityArea(ctx context.Context, cityId int) *GetCityAreaResult { // 测试 param := gorequest.NewParams() param.Set("cityId", cityId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-city-area", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-city-area", params) var response GetCityAreaResponse err = json.Unmarshal(request.ResponseBody, &response) return newGetCityAreaResult(response, request.ResponseBody, request, err) diff --git a/service/pintoto/movie_info_get_city_list.go b/service/pintoto/movie_info_get_city_list.go index 82838538..b34c6ecf 100644 --- a/service/pintoto/movie_info_get_city_list.go +++ b/service/pintoto/movie_info_get_city_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -33,8 +34,8 @@ func newGetCityListResult(result GetCityListResponse, body []byte, http goreques // GetCityList 城市列表 // https://www.showdoc.com.cn/1154868044931571/5865562425538244 -func (c *Client) GetCityList() *GetCityListResult { - request, err := c.request(apiUrl+"/movieapi/movie-info/get-city-list", map[string]interface{}{}) +func (c *Client) GetCityList(ctx context.Context) *GetCityListResult { + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-city-list", map[string]interface{}{}) var response GetCityListResponse err = json.Unmarshal(request.ResponseBody, &response) return newGetCityListResult(response, request.ResponseBody, request, err) diff --git a/service/pintoto/movie_info_get_hot_list.go b/service/pintoto/movie_info_get_hot_list.go index be1ed13b..6b26418e 100644 --- a/service/pintoto/movie_info_get_hot_list.go +++ b/service/pintoto/movie_info_get_hot_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -42,14 +43,14 @@ func newGetHotListResult(result GetHotListResponse, body []byte, http gorequest. } // GetHotList 正在热映 https://www.showdoc.com.cn/1154868044931571/5866125707634369 -func (c *Client) GetHotList(cityId int) *GetHotListResult { +func (c *Client) GetHotList(ctx context.Context, cityId int) *GetHotListResult { // 参数 param := gorequest.NewParams() param.Set("cityId", cityId) // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-hot-list", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-hot-list", params) // 定义 var response GetHotListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_schedule_list.go b/service/pintoto/movie_info_get_schedule_list.go index cbbd7886..9b7bf41a 100644 --- a/service/pintoto/movie_info_get_schedule_list.go +++ b/service/pintoto/movie_info_get_schedule_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -46,14 +47,14 @@ func newGetScheduleListResult(result GetScheduleListResponse, body []byte, http } // GetScheduleList 场次排期 https://www.showdoc.com.cn/1154868044931571/5866708808899217 -func (c *Client) GetScheduleList(cinemaId int) *GetScheduleListResult { +func (c *Client) GetScheduleList(ctx context.Context, cinemaId int) *GetScheduleListResult { // 参数 param := gorequest.NewParams() param.Set("cinemaId", cinemaId) // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-schedule-list", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-schedule-list", params) // 定义 var response GetScheduleListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_sea.go b/service/pintoto/movie_info_get_sea.go index 46dc41fa..fb95d772 100644 --- a/service/pintoto/movie_info_get_sea.go +++ b/service/pintoto/movie_info_get_sea.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -43,14 +44,14 @@ func newGetSeatResult(result GetSeatResponse, body []byte, http gorequest.Respon } // GetSeat 座位 https://www.showdoc.com.cn/1154868044931571/5866824368760475 -func (c *Client) GetSeat(showId string) *GetSeatResult { +func (c *Client) GetSeat(ctx context.Context, showId string) *GetSeatResult { // 参数 param := gorequest.NewParams() param.Set("showId", showId) // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-seat", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-seat", params) // 定义 var response GetSeatResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_show_date.go b/service/pintoto/movie_info_get_show_date.go index a6753bc9..aeaf85a7 100644 --- a/service/pintoto/movie_info_get_show_date.go +++ b/service/pintoto/movie_info_get_show_date.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -26,7 +27,7 @@ func newGetShowDateResult(result GetShowDateResponse, body []byte, http goreques } // GetShowDate 包含某电影的日期 https://www.showdoc.com.cn/1154868044931571/6091788579441818 -func (c *Client) GetShowDate(cityId, filmId int) *GetShowDateResult { +func (c *Client) GetShowDate(ctx context.Context, cityId, filmId int) *GetShowDateResult { // 参数 param := gorequest.NewParams() param.Set("cityId", cityId) @@ -34,7 +35,7 @@ func (c *Client) GetShowDate(cityId, filmId int) *GetShowDateResult { // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-show-date", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-show-date", params) // 定义 var response GetShowDateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_show_list.go b/service/pintoto/movie_info_get_show_list.go index 9315c8c0..2df4081d 100644 --- a/service/pintoto/movie_info_get_show_list.go +++ b/service/pintoto/movie_info_get_show_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -48,7 +49,7 @@ func newGetShowListResult(result GetShowListResponse, body []byte, http goreques } // GetShowList 包含某电影的影院 https://www.showdoc.com.cn/1154868044931571/6067372188376779 -func (c *Client) GetShowList(param GetShowList) *GetShowListResult { +func (c *Client) GetShowList(ctx context.Context, param GetShowList) *GetShowListResult { // api params params := map[string]interface{}{} b, _ := json.Marshal(¶m) @@ -57,7 +58,7 @@ func (c *Client) GetShowList(param GetShowList) *GetShowListResult { for k, v := range m { params[k] = v } - request, err := c.request(apiUrl+"/movieapi/movie-info/get-show-list", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-show-list", params) // 定义 var response GetShowListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movie_info_get_soon_list.go b/service/pintoto/movie_info_get_soon_list.go index c7f88f95..eaaf15d7 100644 --- a/service/pintoto/movie_info_get_soon_list.go +++ b/service/pintoto/movie_info_get_soon_list.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -42,14 +43,14 @@ func newGetSoonListResult(result GetSoonListResponse, body []byte, http goreques } // GetSoonList 即将上映 https://www.showdoc.com.cn/1154868044931571/5866125707634369 -func (c *Client) GetSoonList(cityId int) *GetSoonListResult { +func (c *Client) GetSoonList(ctx context.Context, cityId int) *GetSoonListResult { // 参数 param := gorequest.NewParams() param.Set("cityId", cityId) // 转换 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/movieapi/movie-info/get-soon-list", params) + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-soon-list", params) // 定义 var response GetSoonListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/movieapi.movie-info.get-version.go b/service/pintoto/movieapi.movie-info.get-version.go index 8492911a..ef6c4101 100644 --- a/service/pintoto/movieapi.movie-info.get-version.go +++ b/service/pintoto/movieapi.movie-info.get-version.go @@ -1,6 +1,7 @@ package pintoto import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -24,8 +25,8 @@ func newGetVersionResult(result GetVersionResponse, body []byte, http gorequest. } // GetVersion 获取同步版本号 https://www.showdoc.com.cn/1154868044931571/6566701084841699 -func (c *Client) GetVersion() *GetVersionResult { - request, err := c.request(apiUrl+"/movieapi/movie-info/get-version", map[string]interface{}{}) +func (c *Client) GetVersion(ctx context.Context) *GetVersionResult { + request, err := c.request(ctx, apiUrl+"/movieapi/movie-info/get-version", map[string]interface{}{}) // 定义 var response GetVersionResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/pintoto/request.go b/service/pintoto/request.go index abe829b9..bf16a8bc 100644 --- a/service/pintoto/request.go +++ b/service/pintoto/request.go @@ -1,12 +1,14 @@ package pintoto import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "time" ) // 请求 -func (c *Client) request(url string, params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}) (gorequest.Response, error) { // 公共参数 params["time"] = time.Now().Unix() @@ -28,17 +30,17 @@ func (c *Client) request(url string, params map[string]interface{}) (gorequest.R client.SetParams(params) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/taobao/request.go b/service/taobao/request.go index 296e4645..1e18150d 100644 --- a/service/taobao/request.go +++ b/service/taobao/request.go @@ -1,11 +1,13 @@ package taobao import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gostring" ) -func (c *Client) request(params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, params map[string]interface{}) (gorequest.Response, error) { // 签名 c.Sign(params) @@ -17,17 +19,17 @@ func (c *Client) request(params map[string]interface{}) (gorequest.Response, err client.SetParams(params) // 发起请求 - request, err := client.Get() + request, err := client.Get(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddlewareCustom(gostring.ToString(params["method"]), request) + go c.log.GormMiddlewareCustom(ctx, gostring.ToString(params["method"]), request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddlewareCustom(gostring.ToString(params["method"]), request) + go c.log.MongoMiddlewareCustom(ctx, gostring.ToString(params["method"]), request, go_library.Version()) } return request, err diff --git a/service/taobao/taobao.tbk.dg.newuser.order.get.go b/service/taobao/taobao.tbk.dg.newuser.order.get.go index 3beda724..4e55f472 100644 --- a/service/taobao/taobao.tbk.dg.newuser.order.get.go +++ b/service/taobao/taobao.tbk.dg.newuser.order.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -28,11 +29,11 @@ func newTbkDgNewuserOrderGetResult(result TbkDgNewuserOrderGetResponse, body []b // TbkDgNewuserOrderGet 淘宝客-推广者-新用户订单明细查询 // https://open.taobao.com/api.htm?docId=33892&docType=2 -func (c *Client) TbkDgNewuserOrderGet(notMustParams ...Params) *TbkDgNewuserOrderGetResult { +func (c *Client) TbkDgNewuserOrderGet(ctx context.Context, notMustParams ...Params) *TbkDgNewuserOrderGetResult { // 参数 params := NewParamsWithType("taobao.tbk.dg.newuser.order.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkDgNewuserOrderGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/taobao.tbk.order.details.get.go b/service/taobao/taobao.tbk.order.details.get.go index 7165120d..183a2e98 100644 --- a/service/taobao/taobao.tbk.order.details.get.go +++ b/service/taobao/taobao.tbk.order.details.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -82,11 +83,11 @@ func newTbkOrderDetailsGetResult(result TbkOrderDetailsGetResponse, body []byte, // TbkOrderDetailsGet 淘宝客-推广者-所有订单查询 // https://open.taobao.com/api.htm?docId=43328&docType=2&scopeId=16175 -func (c *Client) TbkOrderDetailsGet(notMustParams ...Params) *TbkOrderDetailsGetResult { +func (c *Client) TbkOrderDetailsGet(ctx context.Context, notMustParams ...Params) *TbkOrderDetailsGetResult { // 参数 params := NewParamsWithType("taobao.tbk.order.details.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkOrderDetailsGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.activity.info.get.go b/service/taobao/tbk.activity.info.get.go index ff3aae3d..13373d57 100644 --- a/service/taobao/tbk.activity.info.get.go +++ b/service/taobao/tbk.activity.info.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -34,12 +35,12 @@ func newTbkActivityInfoGetResult(result TbkActivityInfoGetResponse, body []byte, // TbkActivityInfoGet 淘宝客-推广者-官方活动转链 // https://open.taobao.com/api.htm?spm=a219a.7386797.0.0.5a83669a7rURsF&source=search&docId=48340&docType=2 -func (c *Client) TbkActivityInfoGet(notMustParams ...Params) *TbkActivityInfoGetResult { +func (c *Client) TbkActivityInfoGet(ctx context.Context, notMustParams ...Params) *TbkActivityInfoGetResult { // 参数 params := NewParamsWithType("taobao.tbk.activity.info.get", notMustParams...) params.Set("adzone_id", c.GetAdzoneId()) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkActivityInfoGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.coupon.get.go b/service/taobao/tbk.coupon.get.go index d5efa7a2..54cb2267 100644 --- a/service/taobao/tbk.coupon.get.go +++ b/service/taobao/tbk.coupon.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -58,11 +59,11 @@ func newTbkCouponGetResult(result TbkCouponGetResponse, body []byte, http gorequ // TbkCouponGet 淘宝客-公用-阿里妈妈推广券详情查询 // https://open.taobao.com/api.htm?docId=31106&docType=2 -func (c *Client) TbkCouponGet(notMustParams ...Params) *TbkCouponGetResult { +func (c *Client) TbkCouponGet(ctx context.Context, notMustParams ...Params) *TbkCouponGetResult { // 参数 params := NewParamsWithType("taobao.tbk.coupon.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkCouponGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.dg.material.optional.go b/service/taobao/tbk.dg.material.optional.go index e8c3ad17..cb357151 100644 --- a/service/taobao/tbk.dg.material.optional.go +++ b/service/taobao/tbk.dg.material.optional.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -77,12 +78,12 @@ func newTbkDgMaterialOptionalResult(result TbkDgMaterialOptionalResponse, body [ // TbkDgMaterialOptional 淘宝客-推广者-物料搜索 // https://open.taobao.com/api.htm?docId=35896&docType=2&source=search -func (c *Client) TbkDgMaterialOptional(notMustParams ...Params) *TbkDgMaterialOptionalResult { +func (c *Client) TbkDgMaterialOptional(ctx context.Context, notMustParams ...Params) *TbkDgMaterialOptionalResult { // 参数 params := NewParamsWithType("taobao.tbk.dg.material.optional", notMustParams...) params.Set("adzone_id", c.GetAdzoneId()) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkDgMaterialOptionalResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.dg.optimus.material.go b/service/taobao/tbk.dg.optimus.material.go index c1f8cd2f..3d72fe6a 100644 --- a/service/taobao/tbk.dg.optimus.material.go +++ b/service/taobao/tbk.dg.optimus.material.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -61,12 +62,12 @@ func newTbkDgOptimusMaterialResult(result TbkDgOptimusMaterialResponse, body []b // TbkDgOptimusMaterial 淘宝客-推广者-物料精选 // https://open.taobao.com/api.htm?spm=a219a.7386797.0.0.5d67669aIeQeVI&source=search&docId=33947&docType=2 -func (c *Client) TbkDgOptimusMaterial(notMustParams ...Params) *TbkDgOptimusMaterialResult { +func (c *Client) TbkDgOptimusMaterial(ctx context.Context, notMustParams ...Params) *TbkDgOptimusMaterialResult { // 参数 params := NewParamsWithType("taobao.tbk.dg.optimus.material", notMustParams...) params.Set("adzone_id", c.GetAdzoneId()) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkDgOptimusMaterialResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.item.info.get.go b/service/taobao/tbk.item.info.get.go index 23c4cfff..b483e104 100644 --- a/service/taobao/tbk.item.info.get.go +++ b/service/taobao/tbk.item.info.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -58,11 +59,11 @@ func newTbkItemInfoGetResult(result TbkItemInfoGetResponse, body []byte, http go // TbkItemInfoGet 淘宝客-公用-淘宝客商品详情查询(简版) // https://open.taobao.com/api.htm?docId=24518&docType=2&source=search -func (c *Client) TbkItemInfoGet(notMustParams ...Params) *TbkItemInfoGetResult { +func (c *Client) TbkItemInfoGet(ctx context.Context, notMustParams ...Params) *TbkItemInfoGetResult { // 参数 params := NewParamsWithType("taobao.tbk.item.info.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkItemInfoGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.shop.get.go b/service/taobao/tbk.shop.get.go index 9280a87a..77d9edf9 100644 --- a/service/taobao/tbk.shop.get.go +++ b/service/taobao/tbk.shop.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -35,11 +36,11 @@ func newTbkShopGetResult(result TbkShopGetResponse, body []byte, http gorequest. // TbkShopGet 淘宝客-推广者-店铺搜索 // https://open.taobao.com/api.htm?docId=24521&docType=2 -func (c *Client) TbkShopGet(notMustParams ...Params) *TbkShopGetResult { +func (c *Client) TbkShopGet(ctx context.Context, notMustParams ...Params) *TbkShopGetResult { // 参数 params := NewParamsWithType("taobao.tbk.shop.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkShopGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.shop.recommend.get.go b/service/taobao/tbk.shop.recommend.get.go index 2858fc54..41a8128d 100644 --- a/service/taobao/tbk.shop.recommend.get.go +++ b/service/taobao/tbk.shop.recommend.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -33,11 +34,11 @@ func newTbkShopRecommendGetResult(result TbkShopRecommendGetResponse, body []byt // TbkShopRecommendGet 淘宝客-公用-店铺关联推荐 // https://open.taobao.com/api.htm?docId=24522&docType=2 -func (c *Client) TbkShopRecommendGet(notMustParams ...Params) *TbkShopRecommendGetResult { +func (c *Client) TbkShopRecommendGet(ctx context.Context, notMustParams ...Params) *TbkShopRecommendGetResult { // 参数 params := NewParamsWithType("taobao.tbk.shop.recommend.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkShopRecommendGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.spread.get.go b/service/taobao/tbk.spread.get.go index b49390f4..c0ecb0c2 100644 --- a/service/taobao/tbk.spread.get.go +++ b/service/taobao/tbk.spread.get.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -31,11 +32,11 @@ func newTbkSpreadGetResult(result TbkSpreadGetResponse, body []byte, http gorequ // TbkSpreadGet 淘宝客-公用-长链转短链 // https://open.taobao.com/api.htm?docId=27832&docType=2&source=search -func (c *Client) TbkSpreadGet(notMustParams ...Params) *TbkSpreadGetResult { +func (c *Client) TbkSpreadGet(ctx context.Context, notMustParams ...Params) *TbkSpreadGetResult { // 参数 params := NewParamsWithType("taobao.tbk.spread.get", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkSpreadGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/taobao/tbk.tpwd.create.go b/service/taobao/tbk.tpwd.create.go index f1848340..318a7d05 100644 --- a/service/taobao/tbk.tpwd.create.go +++ b/service/taobao/tbk.tpwd.create.go @@ -1,6 +1,7 @@ package taobao import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -28,11 +29,11 @@ func newTbkTPwdCreateResult(result TbkTPwdCreateResponse, body []byte, http gore // TbkTPwdCreate 淘宝客-公用-淘口令生成 // https://open.taobao.com/api.htm?docId=31127&docType=2&source=search -func (c *Client) TbkTPwdCreate(notMustParams ...Params) *TbkTPwdCreateResult { +func (c *Client) TbkTPwdCreate(ctx context.Context, notMustParams ...Params) *TbkTPwdCreateResult { // 参数 params := NewParamsWithType("taobao.tbk.tpwd.create", notMustParams...) // 请求 - request, err := c.request(params) + request, err := c.request(ctx, params) // 定义 var response TbkTPwdCreateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/cgi-bin.getcallbackip.go b/service/wechatminiprogram/cgi-bin.getcallbackip.go index a6742457..4de119c2 100644 --- a/service/wechatminiprogram/cgi-bin.getcallbackip.go +++ b/service/wechatminiprogram/cgi-bin.getcallbackip.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,9 +26,9 @@ func newGetCallBackIpResult(result GetCallBackIpResponse, body []byte, http gore // GetCallBackIp 获取微信callback IP地址 // callback IP即微信调用开发者服务器所使用的出口IP。 // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html#2.%20%E8%8E%B7%E5%8F%96%E5%BE%AE%E4%BF%A1callback%20IP%E5%9C%B0%E5%9D%80 -func (c *Client) GetCallBackIp() *GetCallBackIpResult { +func (c *Client) GetCallBackIp(ctx context.Context) *GetCallBackIpResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response GetCallBackIpResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/cgi-bin.message.subscribe.send.go b/service/wechatminiprogram/cgi-bin.message.subscribe.send.go index 083f4a10..a2fc008c 100644 --- a/service/wechatminiprogram/cgi-bin.message.subscribe.send.go +++ b/service/wechatminiprogram/cgi-bin.message.subscribe.send.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newSubscribeMessageSendResult(result SubscribeMessageSendResponse, body []b // SubscribeMessageSend 发送订阅消息 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html -func (c *Client) SubscribeMessageSend(notMustParams ...gorequest.Params) *SubscribeMessageSendResult { +func (c *Client) SubscribeMessageSend(ctx context.Context, notMustParams ...gorequest.Params) *SubscribeMessageSendResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/message/subscribe/send?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/message/subscribe/send?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response SubscribeMessageSendResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/cgi-bin.token.go b/service/wechatminiprogram/cgi-bin.token.go index ff3bc785..2d6f4eb5 100644 --- a/service/wechatminiprogram/cgi-bin.token.go +++ b/service/wechatminiprogram/cgi-bin.token.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,9 +29,9 @@ func newCgiBinTokenResult(result CgiBinTokenResponse, body []byte, http goreques // CgiBinToken // 接口调用凭证 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html -func (c *Client) CgiBinToken() *CgiBinTokenResult { +func (c *Client) CgiBinToken(ctx context.Context) *CgiBinTokenResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.getAppId(), c.getAppSecret()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.getAppId(), c.getAppSecret()), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/cgi-bin.token.monitor.go b/service/wechatminiprogram/cgi-bin.token.monitor.go index 744ca925..6edf54c4 100644 --- a/service/wechatminiprogram/cgi-bin.token.monitor.go +++ b/service/wechatminiprogram/cgi-bin.token.monitor.go @@ -6,14 +6,14 @@ import ( "time" ) -func (c *Client) GetAccessTokenMonitor() (string, error) { +func (c *Client) GetAccessTokenMonitor(ctx context.Context) (string, error) { if c.config.RedisClient.Db == nil { return "", errors.New("驱动没有初始化") } - result := c.GetCallBackIp() + result := c.GetCallBackIp(ctx) if len(result.Result.IpList) <= 0 { - token := c.CgiBinToken() - c.config.RedisClient.Db.Set(context.Background(), c.getAccessTokenCacheKeyName(), token.Result.AccessToken, time.Second*7000) + token := c.CgiBinToken(ctx) + c.config.RedisClient.Set(ctx, c.getAccessTokenCacheKeyName(), token.Result.AccessToken, time.Second*7000) return token.Result.AccessToken, nil } return c.config.AccessToken, nil diff --git a/service/wechatminiprogram/cgi-bin.token.rdb.go b/service/wechatminiprogram/cgi-bin.token.rdb.go index bc98f996..f876f78a 100644 --- a/service/wechatminiprogram/cgi-bin.token.rdb.go +++ b/service/wechatminiprogram/cgi-bin.token.rdb.go @@ -1,17 +1,18 @@ package wechatminiprogram import ( + "context" "fmt" "time" ) -func (c *Client) GetAccessToken() string { +func (c *Client) GetAccessToken(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.AccessToken } newCache := c.config.RedisClient.NewSimpleStringCache(c.config.RedisClient.NewStringOperation(), time.Second*7000) newCache.DBGetter = func() string { - token := c.CgiBinToken() + token := c.CgiBinToken(ctx) return token.Result.AccessToken } return newCache.GetCache(c.getAccessTokenCacheKeyName()) diff --git a/service/wechatminiprogram/cgi-bin.wxaapp.createwxaqrcode.go b/service/wechatminiprogram/cgi-bin.wxaapp.createwxaqrcode.go index 86e346b6..6338e9fe 100644 --- a/service/wechatminiprogram/cgi-bin.wxaapp.createwxaqrcode.go +++ b/service/wechatminiprogram/cgi-bin.wxaapp.createwxaqrcode.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newCgiBinWxaAppCreateWxaQrCodeResult(result CgiBinWxaAppCreateWxaQrCodeResp // CgiBinWxaAppCreateWxaQrCode 获取小程序二维码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.createQRCode.html -func (c *Client) CgiBinWxaAppCreateWxaQrCode(notMustParams ...gorequest.Params) *CgiBinWxaAppCreateWxaQrCodeResult { +func (c *Client) CgiBinWxaAppCreateWxaQrCode(ctx context.Context, notMustParams ...gorequest.Params) *CgiBinWxaAppCreateWxaQrCodeResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxaapp/createwxaqrcode?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxaapp/createwxaqrcode?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxaAppCreateWxaQrCodeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/get.go b/service/wechatminiprogram/get.go index e1067b6a..ace1466f 100644 --- a/service/wechatminiprogram/get.go +++ b/service/wechatminiprogram/get.go @@ -1,5 +1,7 @@ package wechatminiprogram +import "context" + func (c *Client) getAppId() string { return c.config.AppId } @@ -8,8 +10,8 @@ func (c *Client) getAppSecret() string { return c.config.AppSecret } -func (c *Client) getAccessToken() string { - c.config.AccessToken = c.GetAccessToken() +func (c *Client) getAccessToken(ctx context.Context) string { + c.config.AccessToken = c.GetAccessToken(ctx) return c.config.AccessToken } diff --git a/service/wechatminiprogram/request.go b/service/wechatminiprogram/request.go index 82f746fa..b4c36c6f 100644 --- a/service/wechatminiprogram/request.go +++ b/service/wechatminiprogram/request.go @@ -1,9 +1,13 @@ package wechatminiprogram -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) // 请求接口 -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -21,17 +25,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatminiprogram/save_img.go b/service/wechatminiprogram/save_img.go index b031bf67..129e59b9 100644 --- a/service/wechatminiprogram/save_img.go +++ b/service/wechatminiprogram/save_img.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "github.com/dtapps/go-library/utils/gorequest" "log" "os" @@ -11,7 +12,7 @@ type SaveImgResponse struct { Name string } -func (c *Client) SaveImg(resp gorequest.Response, dir, saveName string) SaveImgResponse { +func (c *Client) SaveImg(ctx context.Context, resp gorequest.Response, dir, saveName string) SaveImgResponse { // 返回是二进制图片,或者json错误 if resp.ResponseHeader.Get("Content-Type") == "image/jpeg" || resp.ResponseHeader.Get("Content-Type") == "image/png" { // 保存在output目录 diff --git a/service/wechatminiprogram/sns.jscode2session.go b/service/wechatminiprogram/sns.jscode2session.go index 14144747..4fa9172a 100644 --- a/service/wechatminiprogram/sns.jscode2session.go +++ b/service/wechatminiprogram/sns.jscode2session.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,9 +29,9 @@ func newSnsJsCode2sessionResult(result SnsJsCode2sessionResponse, body []byte, h // SnsJsCode2session 登录凭证校验 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html -func (c *Client) SnsJsCode2session(jsCode string) *SnsJsCode2sessionResult { +func (c *Client) SnsJsCode2session(ctx context.Context, jsCode string) *SnsJsCode2sessionResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", c.getAppId(), c.getAppSecret(), jsCode), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", c.getAppId(), c.getAppSecret(), jsCode), map[string]interface{}{}, http.MethodGet) // 定义 var response SnsJsCode2sessionResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/user_info.go b/service/wechatminiprogram/user_info.go index b4feb999..37849eed 100644 --- a/service/wechatminiprogram/user_info.go +++ b/service/wechatminiprogram/user_info.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "crypto/aes" "crypto/cipher" "encoding/base64" @@ -40,7 +41,7 @@ func newUserInfoResult(result UserInfoResponse, err error) *UserInfoResult { } // UserInfo 解密用户信息 -func (c *Client) UserInfo(param UserInfo) *UserInfoResult { +func (c *Client) UserInfo(ctx context.Context, param UserInfo) *UserInfoResult { var response UserInfoResponse aesKey, err := base64.StdEncoding.DecodeString(param.SessionKey) if err != nil { diff --git a/service/wechatminiprogram/user_phone.go b/service/wechatminiprogram/user_phone.go index 54c6be87..6d3b9a37 100644 --- a/service/wechatminiprogram/user_phone.go +++ b/service/wechatminiprogram/user_phone.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "crypto/aes" "crypto/cipher" "encoding/base64" @@ -34,7 +35,7 @@ func newUserPhoneResult(result UserPhoneResponse, err error) *UserPhoneResult { } // UserPhone 解密手机号信息 -func (c *Client) UserPhone(param UserPhone) *UserPhoneResult { +func (c *Client) UserPhone(ctx context.Context, param UserPhone) *UserPhoneResult { var response UserPhoneResponse aesKey, err := base64.StdEncoding.DecodeString(param.SessionKey) if err != nil { diff --git a/service/wechatminiprogram/wxa.business.getliveinfo.go b/service/wechatminiprogram/wxa.business.getliveinfo.go index b3717a38..152b1b27 100644 --- a/service/wechatminiprogram/wxa.business.getliveinfo.go +++ b/service/wechatminiprogram/wxa.business.getliveinfo.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -56,11 +57,11 @@ func newBusinessGetLiveInfoResult(result BusinessGetLiveInfoResponse, body []byt // BusinessGetLiveInfo 获取直播间列表 // 调用此接口获取直播间列表及直播间信息 // https://developers.weixin.qq.com/miniprogram/dev/platform-capabilities/industry/liveplayer/studio-api.html -func (c *Client) BusinessGetLiveInfo(notMustParams ...gorequest.Params) *BusinessGetLiveInfoResult { +func (c *Client) BusinessGetLiveInfo(ctx context.Context, notMustParams ...gorequest.Params) *BusinessGetLiveInfoResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/business/getliveinfo?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/business/getliveinfo?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response BusinessGetLiveInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.business.getuserphonenumber.go b/service/wechatminiprogram/wxa.business.getuserphonenumber.go index 2b6f1464..31208949 100644 --- a/service/wechatminiprogram/wxa.business.getuserphonenumber.go +++ b/service/wechatminiprogram/wxa.business.getuserphonenumber.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -34,13 +35,13 @@ func newWxaBusinessGetUserPhoneNumberResult(result WxaBusinessGetUserPhoneNumber // WxaBusinessGetUserPhoneNumber code换取用户手机号。 每个code只能使用一次,code的有效期为5min // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html -func (c *Client) WxaBusinessGetUserPhoneNumber(code string) *WxaBusinessGetUserPhoneNumberResult { +func (c *Client) WxaBusinessGetUserPhoneNumber(ctx context.Context, code string) *WxaBusinessGetUserPhoneNumberResult { // 参数 param := gorequest.NewParams() param.Set("code", code) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/business/getuserphonenumber?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/business/getuserphonenumber?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaBusinessGetUserPhoneNumberResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.generate_urllink.go b/service/wechatminiprogram/wxa.generate_urllink.go index 4359082c..4a41b4a3 100644 --- a/service/wechatminiprogram/wxa.generate_urllink.go +++ b/service/wechatminiprogram/wxa.generate_urllink.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newWxaGenerateUrlLinkResult(result WxaGenerateUrlLinkResponse, body []byte, // WxaGenerateUrlLink 获取小程序 URL Link,适用于短信、邮件、网页、微信内等拉起小程序的业务场景。通过该接口,可以选择生成到期失效和永久有效的小程序链接,有数量限制,目前仅针对国内非个人主体的小程序开放 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.generate.html -func (c *Client) WxaGenerateUrlLink(notMustParams ...gorequest.Params) *WxaGenerateUrlLinkResult { +func (c *Client) WxaGenerateUrlLink(ctx context.Context, notMustParams ...gorequest.Params) *WxaGenerateUrlLinkResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/generate_urllink?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/generate_urllink?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGenerateUrlLinkResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.generatescheme.go b/service/wechatminiprogram/wxa.generatescheme.go index 1cafccc5..3a602697 100644 --- a/service/wechatminiprogram/wxa.generatescheme.go +++ b/service/wechatminiprogram/wxa.generatescheme.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newWxaGenerateSchemeResult(result WxaGenerateSchemeResponse, body []byte, h // WxaGenerateScheme 获取小程序 scheme 码,适用于短信、邮件、外部网页、微信内等拉起小程序的业务场景。通过该接口,可以选择生成到期失效和永久有效的小程序码,有数量限制,目前仅针对国内非个人主体的小程序开放 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.generate.html -func (c *Client) WxaGenerateScheme(notMustParams ...gorequest.Params) *WxaGenerateSchemeResult { +func (c *Client) WxaGenerateScheme(ctx context.Context, notMustParams ...gorequest.Params) *WxaGenerateSchemeResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/generatescheme?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/generatescheme?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGenerateSchemeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.getwxacode.go b/service/wechatminiprogram/wxa.getwxacode.go index 1861d184..4fe62676 100644 --- a/service/wechatminiprogram/wxa.getwxacode.go +++ b/service/wechatminiprogram/wxa.getwxacode.go @@ -2,6 +2,7 @@ package wechatminiprogram import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -30,11 +31,11 @@ func newWxaGetWxaCodeResult(result WxaGetWxaCodeResponse, body []byte, http gore // WxaGetWxaCode 获取小程序码,适用于需要的码数量较少的业务场景。通过该接口生成的小程序码,永久有效,有数量限制 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html -func (c *Client) WxaGetWxaCode(notMustParams ...gorequest.Params) *WxaGetWxaCodeResult { +func (c *Client) WxaGetWxaCode(ctx context.Context, notMustParams ...gorequest.Params) *WxaGetWxaCodeResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/getwxacode?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/getwxacode?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGetWxaCodeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.getwxacodeunlimit.go b/service/wechatminiprogram/wxa.getwxacodeunlimit.go index 690dd81a..5246b57a 100644 --- a/service/wechatminiprogram/wxa.getwxacodeunlimit.go +++ b/service/wechatminiprogram/wxa.getwxacodeunlimit.go @@ -2,6 +2,7 @@ package wechatminiprogram import ( "bytes" + "context" "encoding/json" "errors" "fmt" @@ -30,11 +31,11 @@ func newWxaGetWxaCodeUnLimitResult(result WxaGetWxaCodeUnLimitResponse, body []b // WxaGetWxaCodeUnLimit 获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html -func (c *Client) WxaGetWxaCodeUnLimit(notMustParams ...gorequest.Params) *WxaGetWxaCodeUnLimitResult { +func (c *Client) WxaGetWxaCodeUnLimit(ctx context.Context, notMustParams ...gorequest.Params) *WxaGetWxaCodeUnLimitResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/getwxacodeunlimit?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/getwxacodeunlimit?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGetWxaCodeUnLimitResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.query_urllink.go b/service/wechatminiprogram/wxa.query_urllink.go index c30bb729..a014b081 100644 --- a/service/wechatminiprogram/wxa.query_urllink.go +++ b/service/wechatminiprogram/wxa.query_urllink.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -44,13 +45,13 @@ func newWxaQueryUrlLinkResult(result WxaQueryUrlLinkResponse, body []byte, http // WxaQueryUrlLink 查询小程序 url_link 配置,及长期有效 quota // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-link/urllink.query.html -func (c *Client) WxaQueryUrlLink(urlLink string) *WxaQueryUrlLinkResult { +func (c *Client) WxaQueryUrlLink(ctx context.Context, urlLink string) *WxaQueryUrlLinkResult { // 参数 param := gorequest.NewParams() param.Set("url_link", urlLink) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/query_urllink?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/query_urllink?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaQueryUrlLinkResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxa.queryscheme.go b/service/wechatminiprogram/wxa.queryscheme.go index cc7ca463..b31fe4b5 100644 --- a/service/wechatminiprogram/wxa.queryscheme.go +++ b/service/wechatminiprogram/wxa.queryscheme.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -37,11 +38,11 @@ func newWxaQuerySchemeResult(result WxaQuerySchemeResponse, body []byte, http go // WxaQueryScheme 查询小程序 scheme 码,及长期有效 quota // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/url-scheme/urlscheme.query.html -func (c *Client) WxaQueryScheme(notMustParams ...gorequest.Params) *WxaQuerySchemeResult { +func (c *Client) WxaQueryScheme(ctx context.Context, notMustParams ...gorequest.Params) *WxaQuerySchemeResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/queryscheme?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/queryscheme?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaQuerySchemeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatminiprogram/wxaapi.feedback.list.go b/service/wechatminiprogram/wxaapi.feedback.list.go index f789d944..ba5b26d5 100644 --- a/service/wechatminiprogram/wxaapi.feedback.list.go +++ b/service/wechatminiprogram/wxaapi.feedback.list.go @@ -1,6 +1,7 @@ package wechatminiprogram import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -36,12 +37,12 @@ func newWxaApiFeedbackListResult(result WxaApiFeedbackListResponse, body []byte, // WxaApiFeedbackList 获取用户反馈列表 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/operation/operation.getFeedback.html -func (c *Client) WxaApiFeedbackList(notMustParams ...gorequest.Params) *WxaApiFeedbackListResult { +func (c *Client) WxaApiFeedbackList(ctx context.Context, notMustParams ...gorequest.Params) *WxaApiFeedbackListResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) - params.Set("access_token", c.getAccessToken()) + params.Set("access_token", c.getAccessToken(ctx)) // 请求 - request, err := c.request(apiUrl+"/wxaapi/feedback/list", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/wxaapi/feedback/list", params, http.MethodGet) // 定义 var response WxaApiFeedbackListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/cgi-bin.ticket.getticket.go b/service/wechatoffice/cgi-bin.ticket.getticket.go index dc704177..5d844bb8 100644 --- a/service/wechatoffice/cgi-bin.ticket.getticket.go +++ b/service/wechatoffice/cgi-bin.ticket.getticket.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,9 +28,9 @@ func newCgiBinTicketGetTicketResult(result CgiBinTicketGetTicketResponse, body [ // CgiBinTicketGetTicket 获取api_ticket // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html -func (c *Client) CgiBinTicketGetTicket(Type string) *CgiBinTicketGetTicketResult { +func (c *Client) CgiBinTicketGetTicket(ctx context.Context, Type string) *CgiBinTicketGetTicketResult { // request - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/ticket/getticket?access_token=%s&type=%s", c.getAccessToken(), Type), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/ticket/getticket?access_token=%s&type=%s", c.getAccessToken(ctx), Type), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinTicketGetTicketResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/cgi-bin.ticket.getticket.monitor.go b/service/wechatoffice/cgi-bin.ticket.getticket.monitor.go index 739a4599..07657793 100644 --- a/service/wechatoffice/cgi-bin.ticket.getticket.monitor.go +++ b/service/wechatoffice/cgi-bin.ticket.getticket.monitor.go @@ -7,16 +7,16 @@ import ( ) // GetJsapiTicketMonitor 监控api_ticket -func (c *Client) GetJsapiTicketMonitor() (string, error) { +func (c *Client) GetJsapiTicketMonitor(ctx context.Context) (string, error) { if c.config.RedisClient.Db == nil { return "", errors.New("驱动没有初始化") } - result := c.DebugCgiBinTicketCheck() + result := c.DebugCgiBinTicketCheck(ctx) if result.Result.Errcode == 0 { return c.config.JsapiTicket, nil } - c.config.AccessToken = c.GetAccessToken() - token := c.CgiBinTicketGetTicket("jsapi") + c.config.AccessToken = c.GetAccessToken(ctx) + token := c.CgiBinTicketGetTicket(ctx, "jsapi") c.config.RedisClient.Db.Set(context.Background(), c.getJsapiTicketCacheKeyName(), token.Result.Ticket, time.Second*7000) return token.Result.Ticket, nil } diff --git a/service/wechatoffice/cgi-bin.ticket.getticket.rdb.go b/service/wechatoffice/cgi-bin.ticket.getticket.rdb.go index 38cf5941..d0a6a238 100644 --- a/service/wechatoffice/cgi-bin.ticket.getticket.rdb.go +++ b/service/wechatoffice/cgi-bin.ticket.getticket.rdb.go @@ -1,18 +1,19 @@ package wechatoffice import ( + "context" "fmt" "time" ) // GetJsapiTicket 获取api_ticket -func (c *Client) GetJsapiTicket() string { +func (c *Client) GetJsapiTicket(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.JsapiTicket } newCache := c.config.RedisClient.NewSimpleStringCache(c.config.RedisClient.NewStringOperation(), time.Second*7000) newCache.DBGetter = func() string { - token := c.CgiBinTicketGetTicket("jsapi") + token := c.CgiBinTicketGetTicket(ctx, "jsapi") return token.Result.Ticket } return newCache.GetCache(c.getJsapiTicketCacheKeyName()) diff --git a/service/wechatoffice/cgi-bin.token.go b/service/wechatoffice/cgi-bin.token.go index c04d8394..dbc5b64c 100644 --- a/service/wechatoffice/cgi-bin.token.go +++ b/service/wechatoffice/cgi-bin.token.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,9 +29,9 @@ func newCgiBinTokenResult(result CgiBinTokenResponse, body []byte, http goreques // CgiBinToken // 接口调用凭证 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html -func (c *Client) CgiBinToken() *CgiBinTokenResult { +func (c *Client) CgiBinToken(ctx context.Context) *CgiBinTokenResult { // request - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.GetAppId(), c.GetAppSecret()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.GetAppId(), c.GetAppSecret()), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/cgi-bin.token.monitor.go b/service/wechatoffice/cgi-bin.token.monitor.go index 7a4dc8c0..a9203e23 100644 --- a/service/wechatoffice/cgi-bin.token.monitor.go +++ b/service/wechatoffice/cgi-bin.token.monitor.go @@ -6,15 +6,15 @@ import ( "time" ) -func (c *Client) GetAccessTokenMonitor() (string, error) { +func (c *Client) GetAccessTokenMonitor(ctx context.Context) (string, error) { if c.config.RedisClient.Db == nil { return "", errors.New("驱动没有初始化") } - result := c.GetCallBackIp() + result := c.GetCallBackIp(ctx) if len(result.Result.IpList) > 0 { return c.config.AccessToken, nil } - token := c.CgiBinToken() + token := c.CgiBinToken(ctx) c.config.RedisClient.Db.Set(context.Background(), c.getAccessTokenCacheKeyName(), token.Result.AccessToken, time.Second*7000) return token.Result.AccessToken, nil } diff --git a/service/wechatoffice/cgi-bin.token.rdb.go b/service/wechatoffice/cgi-bin.token.rdb.go index 7e334c09..784a30d6 100644 --- a/service/wechatoffice/cgi-bin.token.rdb.go +++ b/service/wechatoffice/cgi-bin.token.rdb.go @@ -1,17 +1,18 @@ package wechatoffice import ( + "context" "fmt" "time" ) -func (c *Client) GetAccessToken() string { +func (c *Client) GetAccessToken(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.AccessToken } newCache := c.config.RedisClient.NewSimpleStringCache(c.config.RedisClient.NewStringOperation(), time.Second*7000) newCache.DBGetter = func() string { - token := c.CgiBinToken() + token := c.CgiBinToken(ctx) return token.Result.AccessToken } return newCache.GetCache(c.getAccessTokenCacheKeyName()) diff --git a/service/wechatoffice/cgi-bin.user.get.go b/service/wechatoffice/cgi-bin.user.get.go index 7db419b2..77ccf61f 100644 --- a/service/wechatoffice/cgi-bin.user.get.go +++ b/service/wechatoffice/cgi-bin.user.get.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -29,9 +30,9 @@ func newCgiBinUserGetResult(result CgiBinUserGetResponse, body []byte, http gore // CgiBinUserGet 获取用户列表 // https://developers.weixin.qq.com/doc/offiaccount/User_Management/Getting_a_User_List.html -func (c *Client) CgiBinUserGet(nextOpenid string) *CgiBinUserGetResult { +func (c *Client) CgiBinUserGet(ctx context.Context, nextOpenid string) *CgiBinUserGetResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/user/get?access_token=%s&next_openid=%s", c.getAccessToken(), nextOpenid), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/user/get?access_token=%s&next_openid=%s", c.getAccessToken(ctx), nextOpenid), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinUserGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/cgi-bin.user.info.go b/service/wechatoffice/cgi-bin.user.info.go index bfcd080f..69555a8f 100644 --- a/service/wechatoffice/cgi-bin.user.info.go +++ b/service/wechatoffice/cgi-bin.user.info.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -39,9 +40,9 @@ func newCgiBinUserInfoResult(result CgiBinUserInfoResponse, body []byte, http go // CgiBinUserInfo 获取用户基本信息(UnionID机制) // https://developers.weixin.qq.com/doc/offiaccount/User_Management/Get_users_basic_information_UnionID.html#UinonId -func (c *Client) CgiBinUserInfo(openid string) *CgiBinUserInfoResult { +func (c *Client) CgiBinUserInfo(ctx context.Context, openid string) *CgiBinUserInfoResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", c.getAccessToken(), openid), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN", c.getAccessToken(ctx), openid), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinUserInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/debug.cgi-bin.ticket.check.go b/service/wechatoffice/debug.cgi-bin.ticket.check.go index 12496d42..5df3f9e1 100644 --- a/service/wechatoffice/debug.cgi-bin.ticket.check.go +++ b/service/wechatoffice/debug.cgi-bin.ticket.check.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,9 +26,9 @@ func newDebugCgiBinTicketCheckResult(result DebugCgiBinTicketCheckResponse, body // DebugCgiBinTicketCheck 判断ticket是否合法 // https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign -func (c *Client) DebugCgiBinTicketCheck() *DebugCgiBinTicketCheckResult { +func (c *Client) DebugCgiBinTicketCheck(ctx context.Context) *DebugCgiBinTicketCheckResult { // 请求 - request, err := c.request(fmt.Sprintf("https://mp.weixin.qq.com/debug/cgi-bin/ticket/check?ticket=%s", c.getJsapiTicket()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf("https://mp.weixin.qq.com/debug/cgi-bin/ticket/check?ticket=%s", c.getJsapiTicket(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response DebugCgiBinTicketCheckResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/get.go b/service/wechatoffice/get.go index e257e300..cfcfd1db 100644 --- a/service/wechatoffice/get.go +++ b/service/wechatoffice/get.go @@ -1,5 +1,7 @@ package wechatoffice +import "context" + func (c *Client) GetAppId() string { return c.config.AppId } @@ -8,12 +10,12 @@ func (c *Client) GetAppSecret() string { return c.config.AppSecret } -func (c *Client) getAccessToken() string { - c.config.AccessToken = c.GetAccessToken() +func (c *Client) getAccessToken(ctx context.Context) string { + c.config.AccessToken = c.GetAccessToken(ctx) return c.config.AccessToken } -func (c *Client) getJsapiTicket() string { - c.config.JsapiTicket = c.GetJsapiTicket() +func (c *Client) getJsapiTicket(ctx context.Context) string { + c.config.JsapiTicket = c.GetJsapiTicket(ctx) return c.config.JsapiTicket } diff --git a/service/wechatoffice/getcallbackip.go b/service/wechatoffice/getcallbackip.go index 03ffcf08..25b00af1 100644 --- a/service/wechatoffice/getcallbackip.go +++ b/service/wechatoffice/getcallbackip.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,9 +26,9 @@ func newGetCallBackIpResult(result GetCallBackIpResponse, body []byte, http gore // GetCallBackIp 获取微信callback IP地址 // callback IP即微信调用开发者服务器所使用的出口IP。 // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html#2.%20%E8%8E%B7%E5%8F%96%E5%BE%AE%E4%BF%A1callback%20IP%E5%9C%B0%E5%9D%80 -func (c *Client) GetCallBackIp() *GetCallBackIpResult { +func (c *Client) GetCallBackIp(ctx context.Context) *GetCallBackIpResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response GetCallBackIpResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/message.template.send.go b/service/wechatoffice/message.template.send.go index c0538ee6..0c000c43 100644 --- a/service/wechatoffice/message.template.send.go +++ b/service/wechatoffice/message.template.send.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newMessageTemplateSendResult(result MessageTemplateSendResponse, body []byt // MessageTemplateSend 模板消息 // https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html -func (c *Client) MessageTemplateSend(notMustParams ...gorequest.Params) *MessageTemplateSendResult { +func (c *Client) MessageTemplateSend(ctx context.Context, notMustParams ...gorequest.Params) *MessageTemplateSendResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/message/template/send?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/message/template/send?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response MessageTemplateSendResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/oauth2.go b/service/wechatoffice/oauth2.go index 726a9cf3..9328528c 100644 --- a/service/wechatoffice/oauth2.go +++ b/service/wechatoffice/oauth2.go @@ -1,13 +1,14 @@ package wechatoffice import ( + "context" "fmt" "net/url" ) // Oauth2 用户同意授权,获取code // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0 -func (c *Client) Oauth2(redirectUri, state string) string { +func (c *Client) Oauth2(ctx context.Context, redirectUri, state string) string { param := url.Values{} param.Add("appid", c.GetAppId()) // 公众号的唯一标识 param.Add("redirect_uri", redirectUri) // 授权后重定向的回调链接地址, 请使用 urlEncode 对链接进行处理 diff --git a/service/wechatoffice/request.go b/service/wechatoffice/request.go index b0b66a5f..7a0729cc 100644 --- a/service/wechatoffice/request.go +++ b/service/wechatoffice/request.go @@ -1,9 +1,13 @@ package wechatoffice -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) // 请求接口 -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -21,17 +25,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatoffice/share.go b/service/wechatoffice/share.go index a8d77165..4a7fbb97 100644 --- a/service/wechatoffice/share.go +++ b/service/wechatoffice/share.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "crypto/sha1" "fmt" "github.com/dtapps/go-library/utils/gorandom" @@ -26,9 +27,9 @@ func newShareResult(result ShareResponse, err error) *ShareResult { return &ShareResult{Result: result, Err: err} } -func (c *Client) Share(url string) *ShareResult { - c.getAccessToken() - c.config.JsapiTicket = c.GetJsapiTicket() +func (c *Client) Share(ctx context.Context, url string) *ShareResult { + c.getAccessToken(ctx) + c.config.JsapiTicket = c.GetJsapiTicket(ctx) var response ShareResponse response.AppId = c.GetAppId() response.NonceStr = gorandom.Alphanumeric(32) diff --git a/service/wechatoffice/sns.jscode2session.go b/service/wechatoffice/sns.jscode2session.go index 7be7fbdc..b0afd6a9 100644 --- a/service/wechatoffice/sns.jscode2session.go +++ b/service/wechatoffice/sns.jscode2session.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,9 +27,9 @@ func newSnsJsCode2sessionResult(result SnsJsCode2sessionResponse, body []byte, h return &SnsJsCode2sessionResult{Result: result, Body: body, Http: http, Err: err} } -func (c *Client) SnsJsCode2session(jsCode string) *SnsJsCode2sessionResult { +func (c *Client) SnsJsCode2session(ctx context.Context, jsCode string) *SnsJsCode2sessionResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", c.GetAppId(), c.GetAppSecret(), jsCode), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", c.GetAppId(), c.GetAppSecret(), jsCode), map[string]interface{}{}, http.MethodGet) // 定义 var response SnsJsCode2sessionResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/sns.oauth2.access_token.go b/service/wechatoffice/sns.oauth2.access_token.go index e3bd463a..5882e863 100644 --- a/service/wechatoffice/sns.oauth2.access_token.go +++ b/service/wechatoffice/sns.oauth2.access_token.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,9 +29,9 @@ func newSnsOauth2AccessTokenResult(result SnsOauth2AccessTokenResponse, body []b // SnsOauth2AccessToken 通过code换取网页授权access_token // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0 -func (c *Client) SnsOauth2AccessToken(code string) *SnsOauth2AccessTokenResult { +func (c *Client) SnsOauth2AccessToken(ctx context.Context, code string) *SnsOauth2AccessTokenResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", c.GetAppId(), c.GetAppSecret(), code), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code", c.GetAppId(), c.GetAppSecret(), code), map[string]interface{}{}, http.MethodGet) // 定义 var response SnsOauth2AccessTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatoffice/sns.userinfo.go b/service/wechatoffice/sns.userinfo.go index 34e53274..67e7f90d 100644 --- a/service/wechatoffice/sns.userinfo.go +++ b/service/wechatoffice/sns.userinfo.go @@ -1,6 +1,7 @@ package wechatoffice import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -32,9 +33,9 @@ func newSnsUserinfoResult(result SnsUserinfoResponse, body []byte, http goreques // SnsUserinfo 拉取用户信息(需scope为 snsapi_userinfo) // https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html#0 -func (c *Client) SnsUserinfo(accessToken, openid string) *SnsUserinfoResult { +func (c *Client) SnsUserinfo(ctx context.Context, accessToken, openid string) *SnsUserinfoResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openid), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openid), map[string]interface{}{}, http.MethodGet) // 定义 var response SnsUserinfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.account.getaccountbasicinfo.go b/service/wechatopen/cgi-bin.account.getaccountbasicinfo.go index 407a27ce..123a4df3 100644 --- a/service/wechatopen/cgi-bin.account.getaccountbasicinfo.go +++ b/service/wechatopen/cgi-bin.account.getaccountbasicinfo.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -55,9 +56,9 @@ func newCgiBinAccountGetAccountBasicInfoResult(result CgiBinAccountGetAccountBas // CgiBinAccountGetAccountBasicInfo 获取基本信息 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_Basic_Info/Mini_Program_Information_Settings.html -func (c *Client) CgiBinAccountGetAccountBasicInfo() *CgiBinAccountGetAccountBasicInfoResult { +func (c *Client) CgiBinAccountGetAccountBasicInfo(ctx context.Context) *CgiBinAccountGetAccountBasicInfoResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/account/getaccountbasicinfo?access_token=%v", c.GetAuthorizerAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/account/getaccountbasicinfo?access_token=%v", c.GetAuthorizerAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinAccountGetAccountBasicInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_authorizer_token.go b/service/wechatopen/cgi-bin.component.api_authorizer_token.go index c62a7561..640760c3 100644 --- a/service/wechatopen/cgi-bin.component.api_authorizer_token.go +++ b/service/wechatopen/cgi-bin.component.api_authorizer_token.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,7 +28,7 @@ func newCgiBinComponentApiAuthorizerTokenResult(result CgiBinComponentApiAuthori // CgiBinComponentApiAuthorizerToken 获取/刷新接口调用令牌 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/api_authorizer_token.html -func (c *Client) CgiBinComponentApiAuthorizerToken(authorizerRefreshToken string) *CgiBinComponentApiAuthorizerTokenResult { +func (c *Client) CgiBinComponentApiAuthorizerToken(ctx context.Context, authorizerRefreshToken string) *CgiBinComponentApiAuthorizerTokenResult { // 参数 param := gorequest.NewParams() param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid @@ -35,7 +36,7 @@ func (c *Client) CgiBinComponentApiAuthorizerToken(authorizerRefreshToken string param["authorizer_refresh_token"] = authorizerRefreshToken // 授权码, 会在授权成功时返回给第三方平台 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/api_authorizer_token?component_access_token=%v", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/api_authorizer_token?component_access_token=%v", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentApiAuthorizerTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_component_token.go b/service/wechatopen/cgi-bin.component.api_component_token.go index d3419b5f..32b65777 100644 --- a/service/wechatopen/cgi-bin.component.api_component_token.go +++ b/service/wechatopen/cgi-bin.component.api_component_token.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -24,15 +25,15 @@ func newCgiBinComponentApiComponentTokenResult(result CgiBinComponentApiComponen // CgiBinComponentApiComponentToken 令牌 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/component_access_token.html -func (c *Client) CgiBinComponentApiComponentToken() *CgiBinComponentApiComponentTokenResult { +func (c *Client) CgiBinComponentApiComponentToken(ctx context.Context) *CgiBinComponentApiComponentTokenResult { // 参数 param := gorequest.NewParams() - param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid - param["component_appsecret"] = c.config.ComponentAppSecret // 第三方平台 appsecret - param["component_verify_ticket"] = c.GetComponentVerifyTicket() // 微信后台推送的 ticket + param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid + param["component_appsecret"] = c.config.ComponentAppSecret // 第三方平台 appsecret + param["component_verify_ticket"] = c.GetComponentVerifyTicket(ctx) // 微信后台推送的 ticket params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/cgi-bin/component/api_component_token", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/cgi-bin/component/api_component_token", params, http.MethodPost) // 定义 var response CgiBinComponentApiComponentTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_create_preauthcode.go b/service/wechatopen/cgi-bin.component.api_create_preauthcode.go index a7cbabb7..4c5d7c55 100644 --- a/service/wechatopen/cgi-bin.component.api_create_preauthcode.go +++ b/service/wechatopen/cgi-bin.component.api_create_preauthcode.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,13 +26,13 @@ func newCgiBinComponentApiCreatePreAuthCodenResult(result CgiBinComponentApiCrea // CgiBinComponentApiCreatePreAuthCoden 预授权码 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/pre_auth_code.html -func (c *Client) CgiBinComponentApiCreatePreAuthCoden() *CgiBinComponentApiCreatePreAuthCodenResult { +func (c *Client) CgiBinComponentApiCreatePreAuthCoden(ctx context.Context) *CgiBinComponentApiCreatePreAuthCodenResult { // 参数 param := gorequest.NewParams() param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/api_create_preauthcode?component_access_token=%v", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/api_create_preauthcode?component_access_token=%v", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentApiCreatePreAuthCodenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_get_authorizer_info.go b/service/wechatopen/cgi-bin.component.api_get_authorizer_info.go index 823b8949..37fab16c 100644 --- a/service/wechatopen/cgi-bin.component.api_get_authorizer_info.go +++ b/service/wechatopen/cgi-bin.component.api_get_authorizer_info.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -83,14 +84,14 @@ func newCgiBinComponentApiGetAuthorizerInfoResult(result CgiBinComponentApiGetAu // CgiBinComponentApiGetAuthorizerInfo 获取授权帐号详情 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/api_get_authorizer_info.html -func (c *Client) CgiBinComponentApiGetAuthorizerInfo() *CgiBinComponentApiGetAuthorizerInfoResult { +func (c *Client) CgiBinComponentApiGetAuthorizerInfo(ctx context.Context) *CgiBinComponentApiGetAuthorizerInfoResult { // 参数 param := gorequest.NewParams() param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid param["authorizer_appid"] = c.config.AuthorizerAppid // 授权方 appid params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/api_get_authorizer_info?component_access_token=%v", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/api_get_authorizer_info?component_access_token=%v", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentApiGetAuthorizerInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_query_auth.go b/service/wechatopen/cgi-bin.component.api_query_auth.go index 60fce0cf..5951d948 100644 --- a/service/wechatopen/cgi-bin.component.api_query_auth.go +++ b/service/wechatopen/cgi-bin.component.api_query_auth.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -39,14 +40,14 @@ func newCgiBinComponentApiQueryAuthResult(result CgiBinComponentApiQueryAuthResp // CgiBinComponentApiQueryAuth 使用授权码获取授权信息 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/authorization_info.html -func (c *Client) CgiBinComponentApiQueryAuth(authorizationCode string) *CgiBinComponentApiQueryAuthResult { +func (c *Client) CgiBinComponentApiQueryAuth(ctx context.Context, authorizationCode string) *CgiBinComponentApiQueryAuthResult { // 参数 param := gorequest.NewParams() param["component_appid"] = c.config.ComponentAppId // 第三方平台 appid param["authorization_code"] = authorizationCode // 授权码, 会在授权成功时返回给第三方平台 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/api_query_auth?component_access_token=%v", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/api_query_auth?component_access_token=%v", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentApiQueryAuthResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.api_start_push_ticket.go b/service/wechatopen/cgi-bin.component.api_start_push_ticket.go index 8c6d6bfd..90d45d8a 100644 --- a/service/wechatopen/cgi-bin.component.api_start_push_ticket.go +++ b/service/wechatopen/cgi-bin.component.api_start_push_ticket.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -26,14 +27,14 @@ func newCgiBinComponentApiStartPushTicketResult(result CgiBinComponentApiStartPu // CgiBinComponentApiStartPushTicket 启动ticket推送服务 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/token/component_verify_ticket_service.html -func (c *Client) CgiBinComponentApiStartPushTicket() *CgiBinComponentApiStartPushTicketResult { +func (c *Client) CgiBinComponentApiStartPushTicket(ctx context.Context) *CgiBinComponentApiStartPushTicketResult { // 参数 param := gorequest.NewParams() param["component_appid"] = c.config.ComponentAppId // 平台型第三方平台的appid param["component_secret"] = c.config.ComponentAppSecret // 平台型第三方平台的APPSECRET params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/cgi-bin/component/api_start_push_ticket", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/cgi-bin/component/api_start_push_ticket", params, http.MethodPost) // 定义 var response CgiBinComponentApiStartPushTicketResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.getprivacysetting.go b/service/wechatopen/cgi-bin.component.getprivacysetting.go index 441e50ef..ebe42023 100644 --- a/service/wechatopen/cgi-bin.component.getprivacysetting.go +++ b/service/wechatopen/cgi-bin.component.getprivacysetting.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -58,12 +59,12 @@ func newCgiBinComponentGetPrivacySettingResult(result CgiBinComponentGetPrivacyS // CgiBinComponentGetPrivacySetting 查询小程序用户隐私保护指引 // @privacyVer 1表示现网版本,即,传1则该接口返回的内容是现网版本的;2表示开发版,即,传2则该接口返回的内容是开发版本的。默认是2。 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/privacy_config/get_privacy_setting.html -func (c *Client) CgiBinComponentGetPrivacySetting(privacyVer int) *CgiBinComponentGetPrivacySettingResult { +func (c *Client) CgiBinComponentGetPrivacySetting(ctx context.Context, privacyVer int) *CgiBinComponentGetPrivacySettingResult { // 参数 params := gorequest.NewParams() params["privacy_ver"] = privacyVer // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/getprivacysetting?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/getprivacysetting?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentGetPrivacySettingResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.component.setprivacysetting.go b/service/wechatopen/cgi-bin.component.setprivacysetting.go index bd28f8d1..693e2e23 100644 --- a/service/wechatopen/cgi-bin.component.setprivacysetting.go +++ b/service/wechatopen/cgi-bin.component.setprivacysetting.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newCgiBinComponentSetPrivacySettingResult(result CgiBinComponentSetPrivacyS // CgiBinComponentSetPrivacySetting 配置小程序用户隐私保护指引 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/privacy_config/set_privacy_setting.html -func (c *Client) CgiBinComponentSetPrivacySetting(notMustParams ...gorequest.Params) *CgiBinComponentSetPrivacySettingResult { +func (c *Client) CgiBinComponentSetPrivacySetting(ctx context.Context, notMustParams ...gorequest.Params) *CgiBinComponentSetPrivacySettingResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/component/setprivacysetting?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/component/setprivacysetting?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinComponentSetPrivacySettingResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.get_api_domain_ip.go b/service/wechatopen/cgi-bin.get_api_domain_ip.go index 0c86f18f..04af3cfc 100644 --- a/service/wechatopen/cgi-bin.get_api_domain_ip.go +++ b/service/wechatopen/cgi-bin.get_api_domain_ip.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -24,9 +25,9 @@ func NewGetCallBackIpResult(result GetCallBackIpResponse, body []byte, http gore // CgiBinGetApiDomainIp 获取微信服务器IP地址 // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html -func (c *Client) CgiBinGetApiDomainIp(componentAccessToken string) *GetCallBackIpResult { +func (c *Client) CgiBinGetApiDomainIp(ctx context.Context, componentAccessToken string) *GetCallBackIpResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/get_api_domain_ip?access_token=%s", componentAccessToken), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/get_api_domain_ip?access_token=%s", componentAccessToken), map[string]interface{}{}, http.MethodGet) // 定义 var response GetCallBackIpResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.shorturl.go b/service/wechatopen/cgi-bin.shorturl.go index 7c81f360..23c4794f 100644 --- a/service/wechatopen/cgi-bin.shorturl.go +++ b/service/wechatopen/cgi-bin.shorturl.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,13 +27,13 @@ func newCgiBinShortUrlResult(result CgiBinShortUrlResponse, body []byte, http go // CgiBinShortUrl 将二维码长链接转成短链接 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/shorturl.html -func (c *Client) CgiBinShortUrl(longUrl string) *CgiBinShortUrlResult { +func (c *Client) CgiBinShortUrl(ctx context.Context, longUrl string) *CgiBinShortUrlResult { // 参数 params := gorequest.NewParams() params["action"] = "long2short" // 此处填long2short,代表长链接转短链接 params["long_url"] = longUrl // 需要转换的长链接,支持http://、https://、weixin://wxpay 格式的url // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/shorturl?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/shorturl?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinShortUrlResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.wxopen.qrcodejumpadd.go b/service/wechatopen/cgi-bin.wxopen.qrcodejumpadd.go index b67e5329..2102c02a 100644 --- a/service/wechatopen/cgi-bin.wxopen.qrcodejumpadd.go +++ b/service/wechatopen/cgi-bin.wxopen.qrcodejumpadd.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newCgiBinWxOpenQrCodeJumpAddResult(result CgiBinWxOpenQrCodeJumpAddResponse // CgiBinWxOpenQrCodeJumpAdd 增加或修改二维码规则 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/qrcodejumpadd.html -func (c *Client) CgiBinWxOpenQrCodeJumpAdd(notMustParams ...gorequest.Params) *CgiBinWxOpenQrCodeJumpAddResult { +func (c *Client) CgiBinWxOpenQrCodeJumpAdd(ctx context.Context, notMustParams ...gorequest.Params) *CgiBinWxOpenQrCodeJumpAddResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpadd?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpadd?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxOpenQrCodeJumpAddResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.wxopen.qrcodejumpdelete.go b/service/wechatopen/cgi-bin.wxopen.qrcodejumpdelete.go index 0889f9e7..9b69d1b6 100644 --- a/service/wechatopen/cgi-bin.wxopen.qrcodejumpdelete.go +++ b/service/wechatopen/cgi-bin.wxopen.qrcodejumpdelete.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,12 +26,12 @@ func newCgiBinWxOpenQrCodeJumpDeleteResult(result CgiBinWxOpenQrCodeJumpDeleteRe // CgiBinWxOpenQrCodeJumpDelete 删除已设置的二维码规则 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/qrcodejumpdelete.html -func (c *Client) CgiBinWxOpenQrCodeJumpDelete(prefix string) *CgiBinWxOpenQrCodeJumpDeleteResult { +func (c *Client) CgiBinWxOpenQrCodeJumpDelete(ctx context.Context, prefix string) *CgiBinWxOpenQrCodeJumpDeleteResult { // 参数 params := gorequest.NewParams() params["prefix"] = prefix // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpdelete?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpdelete?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxOpenQrCodeJumpDeleteResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.wxopen.qrcodejumpdownloa.go b/service/wechatopen/cgi-bin.wxopen.qrcodejumpdownloa.go index d03a0a10..ae36514d 100644 --- a/service/wechatopen/cgi-bin.wxopen.qrcodejumpdownloa.go +++ b/service/wechatopen/cgi-bin.wxopen.qrcodejumpdownloa.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newCgiBinWxOpenQrCodeJumpDownloadResult(result CgiBinWxOpenQrCodeJumpDownlo // CgiBinWxOpenQrCodeJumpDownload 获取校验文件名称及内容 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/qrcodejumpdownload.html -func (c *Client) CgiBinWxOpenQrCodeJumpDownload() *CgiBinWxOpenQrCodeJumpDownloadResult { +func (c *Client) CgiBinWxOpenQrCodeJumpDownload(ctx context.Context) *CgiBinWxOpenQrCodeJumpDownloadResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpdownload?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpdownload?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxOpenQrCodeJumpDownloadResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.wxopen.qrcodejumpget.go b/service/wechatopen/cgi-bin.wxopen.qrcodejumpget.go index 314a75c1..63bbbf21 100644 --- a/service/wechatopen/cgi-bin.wxopen.qrcodejumpget.go +++ b/service/wechatopen/cgi-bin.wxopen.qrcodejumpget.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -36,11 +37,11 @@ func newCgiBinWxOpenQrCodeJumpGetResult(result CgiBinWxOpenQrCodeJumpGetResponse // CgiBinWxOpenQrCodeJumpGet 获取已设置的二维码规则 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/qrcodejumpadd.html -func (c *Client) CgiBinWxOpenQrCodeJumpGet() *CgiBinWxOpenQrCodeJumpGetResult { +func (c *Client) CgiBinWxOpenQrCodeJumpGet(ctx context.Context) *CgiBinWxOpenQrCodeJumpGetResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpget?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumpget?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxOpenQrCodeJumpGetResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/cgi-bin.wxopen.qrcodejumppublish.go b/service/wechatopen/cgi-bin.wxopen.qrcodejumppublish.go index 9f83b80b..e0f9faf9 100644 --- a/service/wechatopen/cgi-bin.wxopen.qrcodejumppublish.go +++ b/service/wechatopen/cgi-bin.wxopen.qrcodejumppublish.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,12 +26,12 @@ func newCgiBinWxOpenQrCodeJumpPublishResult(result CgiBinWxOpenQrCodeJumpPublish // CgiBinWxOpenQrCodeJumpPublish 发布已设置的二维码规则 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/qrcode/qrcodejumppublish.html -func (c *Client) CgiBinWxOpenQrCodeJumpPublish(prefix string) *CgiBinWxOpenQrCodeJumpPublishResult { +func (c *Client) CgiBinWxOpenQrCodeJumpPublish(ctx context.Context, prefix string) *CgiBinWxOpenQrCodeJumpPublishResult { // 参数 params := gorequest.NewParams() params["prefix"] = prefix // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumppublish?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/cgi-bin/wxopen/qrcodejumppublish?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response CgiBinWxOpenQrCodeJumpPublishResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/redis.go b/service/wechatopen/redis.go index 00bae90e..f5050d1a 100644 --- a/service/wechatopen/redis.go +++ b/service/wechatopen/redis.go @@ -12,20 +12,20 @@ func (c *Client) getComponentVerifyTicketCacheKeyName() string { } // SetComponentVerifyTicket 设置微信后台推送的ticke -func (c *Client) SetComponentVerifyTicket(componentVerifyTicket string) string { +func (c *Client) SetComponentVerifyTicket(ctx context.Context, componentVerifyTicket string) string { if componentVerifyTicket == "" { return "" } - c.config.RedisClient.Db.Set(context.Background(), c.getComponentVerifyTicketCacheKeyName(), componentVerifyTicket, time.Hour*12) - return c.GetComponentVerifyTicket() + c.config.RedisClient.Set(ctx, c.getComponentVerifyTicketCacheKeyName(), componentVerifyTicket, time.Hour*12) + return c.GetComponentVerifyTicket(ctx) } // GetComponentVerifyTicket 获取微信后台推送的ticke -func (c *Client) GetComponentVerifyTicket() string { +func (c *Client) GetComponentVerifyTicket(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.ComponentVerifyTicket } - result, _ := c.config.RedisClient.Db.Get(context.Background(), c.getComponentVerifyTicketCacheKeyName()).Result() + result, _ := c.config.RedisClient.Get(ctx, c.getComponentVerifyTicketCacheKeyName()).Result() return result } @@ -35,34 +35,34 @@ func (c *Client) getComponentAccessTokenCacheKeyName() string { } // SetComponentAccessToken 设置令牌 -func (c *Client) SetComponentAccessToken(componentAccessToken string) string { +func (c *Client) SetComponentAccessToken(ctx context.Context, componentAccessToken string) string { if componentAccessToken == "" { return "" } - c.config.RedisClient.Db.Set(context.Background(), c.getComponentAccessTokenCacheKeyName(), componentAccessToken, time.Second*7200) - return c.GetComponentAccessToken() + c.config.RedisClient.Set(ctx, c.getComponentAccessTokenCacheKeyName(), componentAccessToken, time.Second*7200) + return c.GetComponentAccessToken(ctx) } // GetComponentAccessToken 获取令牌 -func (c *Client) GetComponentAccessToken() string { +func (c *Client) GetComponentAccessToken(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.ComponentAccessToken } - result, _ := c.config.RedisClient.Db.Get(context.Background(), c.getComponentAccessTokenCacheKeyName()).Result() + result, _ := c.config.RedisClient.Db.Get(ctx, c.getComponentAccessTokenCacheKeyName()).Result() return result } // MonitorComponentAccessToken 监控令牌 -func (c *Client) MonitorComponentAccessToken() string { +func (c *Client) MonitorComponentAccessToken(ctx context.Context) string { // 查询 - componentAccessToken := c.GetComponentAccessToken() + componentAccessToken := c.GetComponentAccessToken(ctx) // 判断 - result := c.CgiBinGetApiDomainIp(componentAccessToken) + result := c.CgiBinGetApiDomainIp(ctx, componentAccessToken) if len(result.Result.IpList) > 0 { return componentAccessToken } // 重新获取 - return c.SetComponentAccessToken(c.CgiBinComponentApiComponentToken().Result.ComponentAccessToken) + return c.SetComponentAccessToken(ctx, c.CgiBinComponentApiComponentToken(ctx).Result.ComponentAccessToken) } // 授权方令牌 @@ -71,33 +71,33 @@ func (c *Client) getAuthorizerAccessTokenCacheKeyName() string { } // SetAuthorizerAccessToken 设置授权方令牌 -func (c *Client) SetAuthorizerAccessToken(authorizerAccessToken string) string { +func (c *Client) SetAuthorizerAccessToken(ctx context.Context, authorizerAccessToken string) string { if authorizerAccessToken == "" { return "" } - c.config.RedisClient.Db.Set(context.Background(), c.getAuthorizerAccessTokenCacheKeyName(), authorizerAccessToken, time.Hour*2) - return c.GetComponentAccessToken() + c.config.RedisClient.Set(ctx, c.getAuthorizerAccessTokenCacheKeyName(), authorizerAccessToken, time.Hour*2) + return c.GetComponentAccessToken(ctx) } // GetAuthorizerAccessToken 获取授权方令牌 -func (c *Client) GetAuthorizerAccessToken() string { +func (c *Client) GetAuthorizerAccessToken(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.AuthorizerAccessToken } - result, _ := c.config.RedisClient.Db.Get(context.Background(), c.getAuthorizerAccessTokenCacheKeyName()).Result() + result, _ := c.config.RedisClient.Get(ctx, c.getAuthorizerAccessTokenCacheKeyName()).Result() return result } // MonitorAuthorizerAccessToken 监控授权方令牌 -func (c *Client) MonitorAuthorizerAccessToken(authorizerRefreshToken string) string { +func (c *Client) MonitorAuthorizerAccessToken(ctx context.Context, authorizerRefreshToken string) string { // 查询 - authorizerAccessToken := c.GetAuthorizerAccessToken() + authorizerAccessToken := c.GetAuthorizerAccessToken(ctx) // 判断 if authorizerAccessToken != "" { return authorizerAccessToken } // 重新获取 - return c.SetAuthorizerAccessToken(c.CgiBinComponentApiAuthorizerToken(authorizerRefreshToken).Result.AuthorizerAccessToken) + return c.SetAuthorizerAccessToken(ctx, c.CgiBinComponentApiAuthorizerToken(ctx, authorizerRefreshToken).Result.AuthorizerAccessToken) } // 预授权码 @@ -106,36 +106,36 @@ func (c *Client) getPreAuthCodeCacheKeyName() string { } // SetPreAuthCode 设置预授权码 -func (c *Client) SetPreAuthCode(preAuthCode string) string { +func (c *Client) SetPreAuthCode(ctx context.Context, preAuthCode string) string { if preAuthCode == "" { return "" } - c.config.RedisClient.Db.Set(context.Background(), c.getPreAuthCodeCacheKeyName(), preAuthCode, time.Second*1700) - return c.GetComponentAccessToken() + c.config.RedisClient.Set(ctx, c.getPreAuthCodeCacheKeyName(), preAuthCode, time.Second*1700) + return c.GetComponentAccessToken(ctx) } // GetPreAuthCode 获取预授权码 -func (c *Client) GetPreAuthCode() string { +func (c *Client) GetPreAuthCode(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.AuthorizerAccessToken } - result, _ := c.config.RedisClient.Db.Get(context.Background(), c.getPreAuthCodeCacheKeyName()).Result() + result, _ := c.config.RedisClient.Get(ctx, c.getPreAuthCodeCacheKeyName()).Result() return result } // DelPreAuthCode 删除预授权码 -func (c *Client) DelPreAuthCode() error { - return c.config.RedisClient.Db.Del(context.Background(), c.getPreAuthCodeCacheKeyName()).Err() +func (c *Client) DelPreAuthCode(ctx context.Context) error { + return c.config.RedisClient.Del(ctx, c.getPreAuthCodeCacheKeyName()).Err() } // MonitorPreAuthCode 监控预授权码 -func (c *Client) MonitorPreAuthCode() string { +func (c *Client) MonitorPreAuthCode(ctx context.Context) string { // 查询 - preAuthCode := c.GetPreAuthCode() + preAuthCode := c.GetPreAuthCode(ctx) // 判断 if preAuthCode != "" { return preAuthCode } // 重新获取 - return c.SetPreAuthCode(c.CgiBinComponentApiCreatePreAuthCoden().Result.PreAuthCode) + return c.SetPreAuthCode(ctx, c.CgiBinComponentApiCreatePreAuthCoden(ctx).Result.PreAuthCode) } diff --git a/service/wechatopen/request.go b/service/wechatopen/request.go index 82320373..bccd3a66 100644 --- a/service/wechatopen/request.go +++ b/service/wechatopen/request.go @@ -1,8 +1,12 @@ package wechatopen -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}, method string) (resp gorequest.Response, err error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (resp gorequest.Response, err error) { // 创建请求 client := c.client @@ -20,17 +24,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatopen/save_img.go b/service/wechatopen/save_img.go index 9d5ae36e..c752dfef 100644 --- a/service/wechatopen/save_img.go +++ b/service/wechatopen/save_img.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "github.com/dtapps/go-library/utils/gorequest" "log" "os" @@ -11,7 +12,7 @@ type SaveImgResponse struct { Name string } -func (c *Client) SaveImg(resp gorequest.Response, dir, saveName string) SaveImgResponse { +func (c *Client) SaveImg(ctx context.Context, resp gorequest.Response, dir, saveName string) SaveImgResponse { // 返回是二进制图片,或者json错误 if resp.ResponseHeader.Get("Content-Type") == "image/jpeg" || resp.ResponseHeader.Get("Content-Type") == "image/png" { // 保存在output目录 diff --git a/service/wechatopen/service_http.authorizer_appid.go b/service/wechatopen/service_http.authorizer_appid.go index c95e8296..35602271 100644 --- a/service/wechatopen/service_http.authorizer_appid.go +++ b/service/wechatopen/service_http.authorizer_appid.go @@ -1,13 +1,13 @@ package wechatopen import ( + "context" "errors" "net/http" - "strconv" ) // ServeHttpAuthorizerAppid 授权跳转 -func (c *Client) ServeHttpAuthorizerAppid(r *http.Request) (resp CgiBinComponentApiQueryAuthResponse, agentUserId string, err error) { +func (c *Client) ServeHttpAuthorizerAppid(ctx context.Context, r *http.Request) (resp CgiBinComponentApiQueryAuthResponse, agentUserId string, err error) { var ( query = r.URL.Query() @@ -25,34 +25,10 @@ func (c *Client) ServeHttpAuthorizerAppid(r *http.Request) (resp CgiBinComponent return resp, agentUserId, errors.New("找不到过期时间参数") } - info := c.CgiBinComponentApiQueryAuth(authCode) + info := c.CgiBinComponentApiQueryAuth(ctx, authCode) if info.Result.AuthorizationInfo.AuthorizerAppid == "" { return resp, agentUserId, errors.New("获取失败") } return info.Result, agentUserId, nil } - -// ToFloat64 string到float64 -func ToFloat64(s string) float64 { - i, _ := strconv.ParseFloat(s, 64) - return i -} - -// ToInt64 string到int64 -func ToInt64(s string) int64 { - i, err := strconv.ParseInt(s, 10, 64) - if err == nil { - return i - } - return int64(ToFloat64(s)) -} - -// ToUint string到uint64 -func ToUint(s string) uint { - i, err := strconv.ParseUint(s, 10, 64) - if err == nil { - return uint(i) - } - return 0 -} diff --git a/service/wechatopen/service_http.verify_ticket.go b/service/wechatopen/service_http.verify_ticket.go index 69aafc96..b6d635e0 100644 --- a/service/wechatopen/service_http.verify_ticket.go +++ b/service/wechatopen/service_http.verify_ticket.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/base64" "encoding/xml" "errors" @@ -26,7 +27,7 @@ type cipherRequestHttpBody struct { } // ServeHttpVerifyTicket 验证票据推送 -func (c *Client) ServeHttpVerifyTicket(r *http.Request) (resp *ResponseServeHttpVerifyTicket, err error) { +func (c *Client) ServeHttpVerifyTicket(ctx context.Context, r *http.Request) (resp *ResponseServeHttpVerifyTicket, err error) { var ( query = r.URL.Query() diff --git a/service/wechatopen/sns.component.jscode2session.go b/service/wechatopen/sns.component.jscode2session.go index 0c8b7e74..340ec772 100644 --- a/service/wechatopen/sns.component.jscode2session.go +++ b/service/wechatopen/sns.component.jscode2session.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "crypto/aes" "crypto/cipher" "encoding/base64" @@ -30,16 +31,16 @@ func newSnsComponentJsCode2sessionResult(result SnsComponentJsCode2sessionRespon // SnsComponentJsCode2session 小程序登录 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/others/WeChat_login.html -func (c *Client) SnsComponentJsCode2session(jsCode string) *SnsComponentJsCode2sessionResult { +func (c *Client) SnsComponentJsCode2session(ctx context.Context, jsCode string) *SnsComponentJsCode2sessionResult { // 参数 params := gorequest.NewParams() - params["appid"] = c.config.AuthorizerAppid // 小程序的 appId - params["js_code"] = jsCode // wx.login 获取的 code - params["grant_type"] = "authorization_code" // 填 authorization_code - params["component_appid"] = c.config.ComponentAppId // 第三方平台 appid - params["component_access_token"] = c.GetComponentAccessToken() // 第三方平台的component_access_token + params["appid"] = c.config.AuthorizerAppid // 小程序的 appId + params["js_code"] = jsCode // wx.login 获取的 code + params["grant_type"] = "authorization_code" // 填 authorization_code + params["component_appid"] = c.config.ComponentAppId // 第三方平台 appid + params["component_access_token"] = c.GetComponentAccessToken(ctx) // 第三方平台的component_access_token // 请求 - request, err := c.request(apiUrl+"/sns/component/jscode2session", params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/sns/component/jscode2session", params, http.MethodGet) // 定义 var response SnsComponentJsCode2sessionResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/tcb.wxpaylist.go b/service/wechatopen/tcb.wxpaylist.go index fe686828..831f0211 100644 --- a/service/wechatopen/tcb.wxpaylist.go +++ b/service/wechatopen/tcb.wxpaylist.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -32,11 +33,11 @@ func newTckWxPayListResult(result TckWxPayListResponse, body []byte, http gorequ // TckWxPayList 获取授权绑定的商户号列表 // https://developers.weixin.qq.com/doc/oplatform/openApi/OpenApiDoc/cloudbase-common/wechatpay/getWechatPayList.html -func (c *Client) TckWxPayList() *TckWxPayListResult { +func (c *Client) TckWxPayList(ctx context.Context) *TckWxPayListResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(apiUrl+"/tcb/wxpaylist?access_token="+c.GetComponentAccessToken(), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/tcb/wxpaylist?access_token="+c.GetComponentAccessToken(ctx), params, http.MethodPost) // 定义 var response TckWxPayListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.addtotemplate.go b/service/wechatopen/wxa.addtotemplate.go index cebb590c..528bfae8 100644 --- a/service/wechatopen/wxa.addtotemplate.go +++ b/service/wechatopen/wxa.addtotemplate.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,13 +26,13 @@ func newWxaAddToTemplateResult(result WxaAddToTemplateResponse, body []byte, htt // WxaAddToTemplate 将草稿添加到代码模板库 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/code_template/addtotemplate.html -func (c *Client) WxaAddToTemplate(draftId string, templateType int) *WxaAddToTemplateResult { +func (c *Client) WxaAddToTemplate(ctx context.Context, draftId string, templateType int) *WxaAddToTemplateResult { // 参数 params := gorequest.NewParams() params["draft_id"] = draftId params["template_type"] = templateType // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/addtotemplate?access_token=%s", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/addtotemplate?access_token=%s", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaAddToTemplateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.bind_tester.go b/service/wechatopen/wxa.bind_tester.go index 1cb9fc29..c28df13a 100644 --- a/service/wechatopen/wxa.bind_tester.go +++ b/service/wechatopen/wxa.bind_tester.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,12 +27,12 @@ func newWxaBindTesterResult(result WxaBindTesterResponse, body []byte, http gore // WxaBindTester 绑定微信用户为体验者 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_AdminManagement/Admin.html -func (c *Client) WxaBindTester(wechatid string) *WxaBindTesterResult { +func (c *Client) WxaBindTester(ctx context.Context, wechatid string) *WxaBindTesterResult { // 参数 params := gorequest.NewParams() params["wechatid"] = wechatid // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/bind_tester?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/bind_tester?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaBindTesterResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.business.getuserphonenumber.go b/service/wechatopen/wxa.business.getuserphonenumber.go index 3b0ef280..b49db846 100644 --- a/service/wechatopen/wxa.business.getuserphonenumber.go +++ b/service/wechatopen/wxa.business.getuserphonenumber.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -34,12 +35,12 @@ func newWxaBusinessGetUserPhoneNumberResult(result WxaBusinessGetUserPhoneNumber // WxaBusinessGetUserPhoneNumber code换取用户手机号。 每个 code 只能使用一次,code的有效期为5min // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/phonenumber/phonenumber.getPhoneNumber.html -func (c *Client) WxaBusinessGetUserPhoneNumber(code string) *WxaBusinessGetUserPhoneNumberResult { +func (c *Client) WxaBusinessGetUserPhoneNumber(ctx context.Context, code string) *WxaBusinessGetUserPhoneNumberResult { // 参数 params := gorequest.NewParams() params.Set("code", code) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/business/getuserphonenumber?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/business/getuserphonenumber?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaBusinessGetUserPhoneNumberResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.commit.go b/service/wechatopen/wxa.commit.go index ef802796..44551be6 100644 --- a/service/wechatopen/wxa.commit.go +++ b/service/wechatopen/wxa.commit.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newWxaCommitResult(result WxaCommitResponse, body []byte, http gorequest.Re // WxaCommit 上传小程序代码并生成体验版 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/commit.html -func (c *Client) WxaCommit(notMustParams ...gorequest.Params) *WxaCommitResult { +func (c *Client) WxaCommit(ctx context.Context, notMustParams ...gorequest.Params) *WxaCommitResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/commit?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/commit?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaCommitResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.deletetemplate.go b/service/wechatopen/wxa.deletetemplate.go index 82c15afd..60114c16 100644 --- a/service/wechatopen/wxa.deletetemplate.go +++ b/service/wechatopen/wxa.deletetemplate.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,12 +26,12 @@ func newWxaDeleteTemplateResult(result WxaDeleteTemplateResponse, body []byte, h // WxaDeleteTemplate 删除指定代码模板 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/code_template/deletetemplate.html -func (c *Client) WxaDeleteTemplate(templateId string) *WxaDeleteTemplateResult { +func (c *Client) WxaDeleteTemplate(ctx context.Context, templateId string) *WxaDeleteTemplateResult { // 参数 params := gorequest.NewParams() params.Set("template_id", templateId) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/deletetemplate?access_token=%s", c.GetComponentAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/deletetemplate?access_token=%s", c.GetComponentAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaDeleteTemplateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_auditstatus.go b/service/wechatopen/wxa.get_auditstatus.go index 248869f6..f035d7cc 100644 --- a/service/wechatopen/wxa.get_auditstatus.go +++ b/service/wechatopen/wxa.get_auditstatus.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -29,12 +30,12 @@ func newWxaGetAuditStatusResult(result WxaGetAuditStatusResponse, body []byte, h // WxaGetAuditStatus 查询指定发布审核单的审核状态 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/get_auditstatus.html -func (c *Client) WxaGetAuditStatus(auditid int64) *WxaGetAuditStatusResult { +func (c *Client) WxaGetAuditStatus(ctx context.Context, auditid int64) *WxaGetAuditStatusResult { // 参数 params := gorequest.NewParams() params.Set("auditid", auditid) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_auditstatus?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_auditstatus?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGetAuditStatusResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_category.go b/service/wechatopen/wxa.get_category.go index ea9ea792..be360ce0 100644 --- a/service/wechatopen/wxa.get_category.go +++ b/service/wechatopen/wxa.get_category.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -33,9 +34,9 @@ func newWxaGetCategoryResult(result WxaGetCategoryResponse, body []byte, http go // WxaGetCategory 获取审核时可填写的类目信息 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/category/get_category.html -func (c *Client) WxaGetCategory() *WxaGetCategoryResult { +func (c *Client) WxaGetCategory(ctx context.Context) *WxaGetCategoryResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_category?access_token=%s", c.GetAuthorizerAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_category?access_token=%s", c.GetAuthorizerAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response WxaGetCategoryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_effective_domain.go b/service/wechatopen/wxa.get_effective_domain.go index 213fc866..fa304d66 100644 --- a/service/wechatopen/wxa.get_effective_domain.go +++ b/service/wechatopen/wxa.get_effective_domain.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -49,11 +50,11 @@ func newWxaGetEffectiveDomainResult(result WxaGetEffectiveDomainResponse, body [ // WxaGetEffectiveDomain 获取发布后生效服务器域名列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_Basic_Info/get_effective_domain.html -func (c *Client) WxaGetEffectiveDomain(notMustParams ...gorequest.Params) *WxaGetEffectiveDomainResult { +func (c *Client) WxaGetEffectiveDomain(ctx context.Context, notMustParams ...gorequest.Params) *WxaGetEffectiveDomainResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_effective_domain?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_effective_domain?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGetEffectiveDomainResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_latest_auditstatus.go b/service/wechatopen/wxa.get_latest_auditstatus.go index 693a5c40..3377e4c5 100644 --- a/service/wechatopen/wxa.get_latest_auditstatus.go +++ b/service/wechatopen/wxa.get_latest_auditstatus.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -29,9 +30,9 @@ func newWxaGetLatestAuditStatusResult(result WxaGetLatestAuditStatusResponse, bo // WxaGetLatestAuditStatus 查询最新一次提交的审核状态 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/get_auditstatus.html -func (c *Client) WxaGetLatestAuditStatus() *WxaGetLatestAuditStatusResult { +func (c *Client) WxaGetLatestAuditStatus(ctx context.Context) *WxaGetLatestAuditStatusResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_latest_auditstatus?access_token=%s", c.GetAuthorizerAccessToken()), map[string]interface{}{}, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_latest_auditstatus?access_token=%s", c.GetAuthorizerAccessToken(ctx)), map[string]interface{}{}, http.MethodPost) // 定义 var response WxaGetLatestAuditStatusResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_page.go b/service/wechatopen/wxa.get_page.go index b72e5807..369f0fe5 100644 --- a/service/wechatopen/wxa.get_page.go +++ b/service/wechatopen/wxa.get_page.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,9 +27,9 @@ func newWxaGetPageResult(result WxaGetPageResponse, body []byte, http gorequest. // WxaGetPage 获取已上传的代码的页面列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/get_page.html -func (c *Client) WxaGetPage() *WxaGetPageResult { +func (c *Client) WxaGetPage(ctx context.Context) *WxaGetPageResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_page?access_token=%s", c.GetAuthorizerAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_page?access_token=%s", c.GetAuthorizerAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response WxaGetPageResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.get_qrcode.go b/service/wechatopen/wxa.get_qrcode.go index 3ff212f8..6228b9c7 100644 --- a/service/wechatopen/wxa.get_qrcode.go +++ b/service/wechatopen/wxa.get_qrcode.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,14 +26,14 @@ func newWxaGetQrcodeResult(result WxaGetQrcodeResponse, body []byte, http gorequ // WxaGetQrcode 获取体验版二维码 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/get_qrcode.html -func (c *Client) WxaGetQrcode(path string) *WxaGetQrcodeResult { +func (c *Client) WxaGetQrcode(ctx context.Context, path string) *WxaGetQrcodeResult { // 参数 params := gorequest.NewParams() if path != "" { params["path"] = path // 指定二维码扫码后直接进入指定页面并可同时带上参数) } // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/get_qrcode?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/get_qrcode?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodGet) // 定义 var response WxaGetQrcodeResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.gettemplatedraftlist.go b/service/wechatopen/wxa.gettemplatedraftlist.go index 2e080559..8cb56ad1 100644 --- a/service/wechatopen/wxa.gettemplatedraftlist.go +++ b/service/wechatopen/wxa.gettemplatedraftlist.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -35,9 +36,9 @@ func newWxaGetTemplateDraftListResult(result WxaGetTemplateDraftListResponse, bo // WxaGetTemplateDraftList 获取代码草稿列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/code_template/gettemplatedraftlist.html -func (c *Client) WxaGetTemplateDraftList() *WxaGetTemplateDraftListResult { +func (c *Client) WxaGetTemplateDraftList(ctx context.Context) *WxaGetTemplateDraftListResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/gettemplatedraftlist?access_token=%s", c.GetComponentAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/gettemplatedraftlist?access_token=%s", c.GetComponentAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response WxaGetTemplateDraftListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.gettemplatelist.go b/service/wechatopen/wxa.gettemplatelist.go index a803218d..66b31864 100644 --- a/service/wechatopen/wxa.gettemplatelist.go +++ b/service/wechatopen/wxa.gettemplatelist.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -36,9 +37,9 @@ func newWxaGetTemplateListResult(result WxaGetTemplateListResponse, body []byte, // WxaGetTemplateList 获取代码模板列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/ThirdParty/code_template/gettemplatelist.html -func (c *Client) WxaGetTemplateList() *WxaGetTemplateListResult { +func (c *Client) WxaGetTemplateList(ctx context.Context) *WxaGetTemplateListResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/gettemplatelist?access_token=%s", c.GetComponentAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/gettemplatelist?access_token=%s", c.GetComponentAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response WxaGetTemplateListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.getversioninfo.go b/service/wechatopen/wxa.getversioninfo.go index cb6cc0a1..968d93ac 100644 --- a/service/wechatopen/wxa.getversioninfo.go +++ b/service/wechatopen/wxa.getversioninfo.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "errors" "fmt" @@ -36,13 +37,13 @@ func newWxaGetVersionInfoResult(result WxaGetVersionInfoResponse, body []byte, h // WxaGetVersionInfo 查询小程序版本信息 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/get_versioninfo.html -func (c *Client) WxaGetVersionInfo() *WxaGetVersionInfoResult { - accessToken := c.GetAuthorizerAccessToken() +func (c *Client) WxaGetVersionInfo(ctx context.Context) *WxaGetVersionInfoResult { + accessToken := c.GetAuthorizerAccessToken(ctx) if accessToken == "" { return newWxaGetVersionInfoResult(WxaGetVersionInfoResponse{}, nil, gorequest.Response{}, errors.New("访问令牌为空")) } // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/getversioninfo?access_token=%s", accessToken), map[string]interface{}{}, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/getversioninfo?access_token=%s", accessToken), map[string]interface{}{}, http.MethodPost) // 定义 var response WxaGetVersionInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.getwxacodeunlimit.go b/service/wechatopen/wxa.getwxacodeunlimit.go index 0535f7fd..28e39235 100644 --- a/service/wechatopen/wxa.getwxacodeunlimit.go +++ b/service/wechatopen/wxa.getwxacodeunlimit.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newWxaGetWxaCodeUnLimitResult(result WxaGetWxaCodeUnLimitResponse, body []b // WxaGetWxaCodeUnLimit 获取小程序码,适用于需要的码数量极多的业务场景。通过该接口生成的小程序码,永久有效,数量暂无限制 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.getUnlimited.html -func (c *Client) WxaGetWxaCodeUnLimit(notMustParams ...gorequest.Params) *WxaGetWxaCodeUnLimitResult { +func (c *Client) WxaGetWxaCodeUnLimit(ctx context.Context, notMustParams ...gorequest.Params) *WxaGetWxaCodeUnLimitResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/getwxacodeunlimit?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/getwxacodeunlimit?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaGetWxaCodeUnLimitResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.memberauth.go b/service/wechatopen/wxa.memberauth.go index 9b020ecf..fea95ca9 100644 --- a/service/wechatopen/wxa.memberauth.go +++ b/service/wechatopen/wxa.memberauth.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "errors" "fmt" @@ -29,8 +30,8 @@ func newWxaMemberAuthResult(result WxaMemberAuthResponse, body []byte, http gore // WxaMemberAuth 获取体验者列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_AdminManagement/memberauth.html -func (c *Client) WxaMemberAuth() *WxaMemberAuthResult { - accessToken := c.GetAuthorizerAccessToken() +func (c *Client) WxaMemberAuth(ctx context.Context) *WxaMemberAuthResult { + accessToken := c.GetAuthorizerAccessToken(ctx) if accessToken == "" { return newWxaMemberAuthResult(WxaMemberAuthResponse{}, nil, gorequest.Response{}, errors.New("访问令牌为空")) } @@ -38,7 +39,7 @@ func (c *Client) WxaMemberAuth() *WxaMemberAuthResult { params := gorequest.NewParams() params["action"] = "get_experiencer" // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/memberauth?access_token=%s", accessToken), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/memberauth?access_token=%s", accessToken), params, http.MethodPost) // 定义 var response WxaMemberAuthResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.modify_domain.go b/service/wechatopen/wxa.modify_domain.go index 12e677eb..042bf395 100644 --- a/service/wechatopen/wxa.modify_domain.go +++ b/service/wechatopen/wxa.modify_domain.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -38,11 +39,11 @@ func newWxaModifyDomainResult(result WxaModifyDomainResponse, body []byte, http // WxaModifyDomain 设置服务器域名 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_Basic_Info/Server_Address_Configuration.html -func (c *Client) WxaModifyDomain(notMustParams ...gorequest.Params) *WxaModifyDomainResult { +func (c *Client) WxaModifyDomain(ctx context.Context, notMustParams ...gorequest.Params) *WxaModifyDomainResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/modify_domain?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/modify_domain?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaModifyDomainResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.modify_domain_directly.go b/service/wechatopen/wxa.modify_domain_directly.go index d2cb62ae..86e429e6 100644 --- a/service/wechatopen/wxa.modify_domain_directly.go +++ b/service/wechatopen/wxa.modify_domain_directly.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newWxaModifyDomainDirectlyResult(result WxaModifyDomainDirectlyResponse, bo // WxaModifyDomainDirectly 快速设置小程序服务器域名 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_Basic_Info/modify_domain_directly.html -func (c *Client) WxaModifyDomainDirectly(notMustParams ...gorequest.Params) *WxaModifyDomainDirectlyResult { +func (c *Client) WxaModifyDomainDirectly(ctx context.Context, notMustParams ...gorequest.Params) *WxaModifyDomainDirectlyResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/modify_domain_directly?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/modify_domain_directly?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaModifyDomainDirectlyResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.release.go b/service/wechatopen/wxa.release.go index 6c01d6c2..c571f05b 100644 --- a/service/wechatopen/wxa.release.go +++ b/service/wechatopen/wxa.release.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newWxaReleaseResult(result WxaReleaseResponse, body []byte, http gorequest. // WxaRelease 发布已通过审核的小程序 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/release.html -func (c *Client) WxaRelease() *WxaReleaseResult { +func (c *Client) WxaRelease(ctx context.Context) *WxaReleaseResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/release?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/release?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaReleaseResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.security.apply_privacy_interface.go b/service/wechatopen/wxa.security.apply_privacy_interface.go index 7fb0f92e..48c65354 100644 --- a/service/wechatopen/wxa.security.apply_privacy_interface.go +++ b/service/wechatopen/wxa.security.apply_privacy_interface.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newWxaSecurityApplyPrivacyInterfaceResult(result WxaSecurityApplyPrivacyInt // WxaSecurityApplyPrivacyInterface 申请接口 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/apply_api/apply_privacy_interface.html -func (c *Client) WxaSecurityApplyPrivacyInterface(notMustParams ...gorequest.Params) *WxaSecurityApplyPrivacyInterfaceResult { +func (c *Client) WxaSecurityApplyPrivacyInterface(ctx context.Context, notMustParams ...gorequest.Params) *WxaSecurityApplyPrivacyInterfaceResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/security/apply_privacy_interface?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/security/apply_privacy_interface?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaSecurityApplyPrivacyInterfaceResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.security.get_privacy_interface.go b/service/wechatopen/wxa.security.get_privacy_interface.go index 666faca3..389fd31f 100644 --- a/service/wechatopen/wxa.security.get_privacy_interface.go +++ b/service/wechatopen/wxa.security.get_privacy_interface.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -36,11 +37,11 @@ func newWxaSecurityGetPrivacyInterfaceResult(result WxaSecurityGetPrivacyInterfa // WxaSecurityGetPrivacyInterface 获取接口列表 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/apply_api/get_privacy_interface.html -func (c *Client) WxaSecurityGetPrivacyInterface() *WxaSecurityGetPrivacyInterfaceResult { +func (c *Client) WxaSecurityGetPrivacyInterface(ctx context.Context) *WxaSecurityGetPrivacyInterfaceResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/security/get_privacy_interface?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/security/get_privacy_interface?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodGet) // 定义 var response WxaSecurityGetPrivacyInterfaceResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.submit_audit.go b/service/wechatopen/wxa.submit_audit.go index 9dab3bf4..5795e992 100644 --- a/service/wechatopen/wxa.submit_audit.go +++ b/service/wechatopen/wxa.submit_audit.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newWxaSubmitAuditResult(result WxaSubmitAuditResponse, body []byte, http go // WxaSubmitAudit 提交审核 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/code/submit_audit.html -func (c *Client) WxaSubmitAudit(notMustParams ...gorequest.Params) *WxaSubmitAuditResult { +func (c *Client) WxaSubmitAudit(ctx context.Context, notMustParams ...gorequest.Params) *WxaSubmitAuditResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/submit_audit?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/submit_audit?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaSubmitAuditResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatopen/wxa.unbind_tester.go b/service/wechatopen/wxa.unbind_tester.go index 85443a0c..4413b628 100644 --- a/service/wechatopen/wxa.unbind_tester.go +++ b/service/wechatopen/wxa.unbind_tester.go @@ -1,6 +1,7 @@ package wechatopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,7 +26,7 @@ func newWxaUnbindTesterResult(result WxaUnbindTesterResponse, body []byte, http // WxaUnbindTester 解除绑定体验者 // https://developers.weixin.qq.com/doc/oplatform/Third-party_Platforms/2.0/api/Mini_Program_AdminManagement/unbind_tester.html -func (c *Client) WxaUnbindTester(wechatid, userstr string) *WxaUnbindTesterResult { +func (c *Client) WxaUnbindTester(ctx context.Context, wechatid, userstr string) *WxaUnbindTesterResult { // 参数 params := gorequest.NewParams() if wechatid != "" { @@ -33,7 +34,7 @@ func (c *Client) WxaUnbindTester(wechatid, userstr string) *WxaUnbindTesterResul } params["userstr"] = userstr // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/wxa/unbind_tester?access_token=%s", c.GetAuthorizerAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/wxa/unbind_tester?access_token=%s", c.GetAuthorizerAccessToken(ctx)), params, http.MethodPost) // 定义 var response WxaUnbindTesterResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatpayapiv2/mmpaymkttransfers.gettransferinfo.go b/service/wechatpayapiv2/mmpaymkttransfers.gettransferinfo.go index aa14c276..545d64fe 100644 --- a/service/wechatpayapiv2/mmpaymkttransfers.gettransferinfo.go +++ b/service/wechatpayapiv2/mmpaymkttransfers.gettransferinfo.go @@ -1,6 +1,7 @@ package wechatpayapiv2 import ( + "context" "encoding/xml" "github.com/dtapps/go-library/utils/gorandom" "github.com/dtapps/go-library/utils/gorequest" @@ -40,7 +41,7 @@ func newTransfersQueryResult(result TransfersQueryResponse, body []byte, http go // TransfersQuery // 付款到零钱 - 查询付款 // https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_3 -func (c *Client) TransfersQuery(partnerTradeNo string) *TransfersQueryResult { +func (c *Client) TransfersQuery(ctx context.Context, partnerTradeNo string) *TransfersQueryResult { cert, err := c.P12ToPem() // 参数 params := NewParams() @@ -51,7 +52,7 @@ func (c *Client) TransfersQuery(partnerTradeNo string) *TransfersQueryResult { // 签名 params.Set("sign", c.getMd5Sign(params)) // 请求 - request, err := c.request(apiUrl+"/mmpaymkttransfers/gettransferinfo", params, cert) + request, err := c.request(ctx, apiUrl+"/mmpaymkttransfers/gettransferinfo", params, cert) // 定义 var response TransfersQueryResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatpayapiv2/mmpaymkttransfers.promotion.transfers.go b/service/wechatpayapiv2/mmpaymkttransfers.promotion.transfers.go index 1026c3e6..6bb05231 100644 --- a/service/wechatpayapiv2/mmpaymkttransfers.promotion.transfers.go +++ b/service/wechatpayapiv2/mmpaymkttransfers.promotion.transfers.go @@ -1,6 +1,7 @@ package wechatpayapiv2 import ( + "context" "encoding/xml" "github.com/dtapps/go-library/utils/gorandom" "github.com/dtapps/go-library/utils/gorequest" @@ -35,7 +36,7 @@ func newTransfersResult(result TransfersResponse, body []byte, http gorequest.Re // Transfers // 付款到零钱 - 付款 // https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_2 -func (c *Client) Transfers(partnerTradeNo, openid string, amount int64, desc string) *TransfersResult { +func (c *Client) Transfers(ctx context.Context, partnerTradeNo, openid string, amount int64, desc string) *TransfersResult { cert, err := c.P12ToPem() // 参数 params := NewParams() @@ -50,7 +51,7 @@ func (c *Client) Transfers(partnerTradeNo, openid string, amount int64, desc str // 签名 params.Set("sign", c.getMd5Sign(params)) // 请求 - request, err := c.request(apiUrl+"/mmpaymkttransfers/promotion/transfers", params, cert) + request, err := c.request(ctx, apiUrl+"/mmpaymkttransfers/promotion/transfers", params, cert) // 定义 var response TransfersResponse err = xml.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatpayapiv2/request.go b/service/wechatpayapiv2/request.go index 61fa48dc..073738fb 100644 --- a/service/wechatpayapiv2/request.go +++ b/service/wechatpayapiv2/request.go @@ -1,11 +1,13 @@ package wechatpayapiv2 import ( + "context" "crypto/tls" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" ) -func (c *Client) request(url string, params map[string]interface{}, cert *tls.Certificate) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, cert *tls.Certificate) (gorequest.Response, error) { // 创建请求 client := c.client @@ -23,17 +25,17 @@ func (c *Client) request(url string, params map[string]interface{}, cert *tls.Ce client.SetP12Cert(cert) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddlewareXml(request) + go c.log.GormMiddlewareXml(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddlewareXml(request) + go c.log.MongoMiddlewareXml(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatpayapiv3/merchant-service.complaints-v2.go b/service/wechatpayapiv3/merchant-service.complaints-v2.go index d4bada0b..f49c145c 100644 --- a/service/wechatpayapiv3/merchant-service.complaints-v2.go +++ b/service/wechatpayapiv3/merchant-service.complaints-v2.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -63,11 +64,11 @@ func newMerchantServiceComplaintsV2Result(result MerchantServiceComplaintsV2Resp // MerchantServiceComplaintsV2 查询投诉单列表API // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter10_2_11.shtml -func (c *Client) MerchantServiceComplaintsV2(notMustParams ...gorequest.Params) *MerchantServiceComplaintsV2Result { +func (c *Client) MerchantServiceComplaintsV2(ctx context.Context, notMustParams ...gorequest.Params) *MerchantServiceComplaintsV2Result { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/v3/merchant-service/complaints-v2", params, http.MethodGet, false) + request, err := c.request(ctx, apiUrl+"/v3/merchant-service/complaints-v2", params, http.MethodGet, false) if err != nil { return newMerchantServiceComplaintsV2Result(MerchantServiceComplaintsV2Response{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/pay.jsapi.go b/service/wechatpayapiv3/pay.jsapi.go index deea7f97..8c17fff4 100644 --- a/service/wechatpayapiv3/pay.jsapi.go +++ b/service/wechatpayapiv3/pay.jsapi.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "fmt" "github.com/dtapps/go-library/utils/gorandom" "time" @@ -22,7 +23,7 @@ type GetJsApiResult struct { } // GetJsApi JSAPI调起支付API https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_4.shtml -func (c *Client) GetJsApi(param GetJsApi) (result GetJsApiResult, err error) { +func (c *Client) GetJsApi(ctx context.Context, param GetJsApi) (result GetJsApiResult, err error) { // sign params timeStamp := time.Now().Unix() diff --git a/service/wechatpayapiv3/pay.transactions.id.go b/service/wechatpayapiv3/pay.transactions.id.go index ac10ad73..bd01ac96 100644 --- a/service/wechatpayapiv3/pay.transactions.id.go +++ b/service/wechatpayapiv3/pay.transactions.id.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -63,9 +64,9 @@ func newPayTransactionsIdResult(result PayTransactionsIdResponse, body []byte, h } // PayTransactionsId 微信支付订单号查询 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_2.shtml -func (c *Client) PayTransactionsId(transactionId string) *PayTransactionsIdResult { +func (c *Client) PayTransactionsId(ctx context.Context, transactionId string) *PayTransactionsIdResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/transactions/id/%s?mchid=%s", transactionId, c.GetMchId()), map[string]interface{}{}, http.MethodGet, true) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/transactions/id/%s?mchid=%s", transactionId, c.GetMchId()), map[string]interface{}{}, http.MethodGet, true) if err != nil { return newPayTransactionsIdResult(PayTransactionsIdResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/pay.transactions.jsapi.go b/service/wechatpayapiv3/pay.transactions.jsapi.go index 6456ef6f..e0e31f2f 100644 --- a/service/wechatpayapiv3/pay.transactions.jsapi.go +++ b/service/wechatpayapiv3/pay.transactions.jsapi.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -23,11 +24,11 @@ func newPayTransactionsJsapiResult(result PayTransactionsJsapiResponse, body []b // PayTransactionsJsapi 小程序 JSAPI下单 // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_5_1.shtml -func (c *Client) PayTransactionsJsapi(notMustParams ...gorequest.Params) *PayTransactionsJsapiResult { +func (c *Client) PayTransactionsJsapi(ctx context.Context, notMustParams ...gorequest.Params) *PayTransactionsJsapiResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/v3/pay/transactions/jsapi", params, http.MethodPost, true) + request, err := c.request(ctx, apiUrl+"/v3/pay/transactions/jsapi", params, http.MethodPost, true) if err != nil { return newPayTransactionsJsapiResult(PayTransactionsJsapiResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/pay.transactions.out-trade-no.close.go b/service/wechatpayapiv3/pay.transactions.out-trade-no.close.go index b34a1a5b..e3245873 100644 --- a/service/wechatpayapiv3/pay.transactions.out-trade-no.close.go +++ b/service/wechatpayapiv3/pay.transactions.out-trade-no.close.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "fmt" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -17,11 +18,11 @@ func newPayTransactionsOutTradeNoCloseResult(body []byte, http gorequest.Respons } // PayTransactionsOutTradeNoClose 关闭订单API https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_3.shtml -func (c *Client) PayTransactionsOutTradeNoClose(OutTradeNo string) *PayTransactionsOutTradeNoCloseResult { +func (c *Client) PayTransactionsOutTradeNoClose(ctx context.Context, OutTradeNo string) *PayTransactionsOutTradeNoCloseResult { // 参数 params := gorequest.NewParams() params["mchid"] = c.GetMchId() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/transactions/out-trade-no/%s/close", OutTradeNo), params, http.MethodPost, false) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/transactions/out-trade-no/%s/close", OutTradeNo), params, http.MethodPost, false) return newPayTransactionsOutTradeNoCloseResult(request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/pay.transactions.out-trade-no.go b/service/wechatpayapiv3/pay.transactions.out-trade-no.go index 901febb4..a9208e8c 100644 --- a/service/wechatpayapiv3/pay.transactions.out-trade-no.go +++ b/service/wechatpayapiv3/pay.transactions.out-trade-no.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -63,9 +64,9 @@ func newPayTransactionsOutTradeNoResult(result PayTransactionsOutTradeNoResponse } // PayTransactionsOutTradeNo 商户订单号查询 https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_2.shtml -func (c *Client) PayTransactionsOutTradeNo(outTradeNo string) *PayTransactionsOutTradeNoResult { +func (c *Client) PayTransactionsOutTradeNo(ctx context.Context, outTradeNo string) *PayTransactionsOutTradeNoResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/transactions/out-trade-no/%s?mchid=%s", outTradeNo, c.GetMchId()), map[string]interface{}{}, http.MethodGet, true) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/transactions/out-trade-no/%s?mchid=%s", outTradeNo, c.GetMchId()), map[string]interface{}{}, http.MethodGet, true) if err != nil { return newPayTransactionsOutTradeNoResult(PayTransactionsOutTradeNoResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/refund.domestic.refunds.go b/service/wechatpayapiv3/refund.domestic.refunds.go index 67053209..d282fca5 100644 --- a/service/wechatpayapiv3/refund.domestic.refunds.go +++ b/service/wechatpayapiv3/refund.domestic.refunds.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -60,11 +61,11 @@ func newRefundDomesticRefundsResult(result RefundDomesticRefundsResponse, body [ } // RefundDomesticRefunds 申请退款API https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter6_1_26.shtml -func (c *Client) RefundDomesticRefunds(notMustParams ...gorequest.Params) *RefundDomesticRefundsResult { +func (c *Client) RefundDomesticRefunds(ctx context.Context, notMustParams ...gorequest.Params) *RefundDomesticRefundsResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/v3/refund/domestic/refunds", params, http.MethodPost, false) + request, err := c.request(ctx, apiUrl+"/v3/refund/domestic/refunds", params, http.MethodPost, false) if err != nil { return newRefundDomesticRefundsResult(RefundDomesticRefundsResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/refund.domestic.refunds.out_refund_no.go b/service/wechatpayapiv3/refund.domestic.refunds.out_refund_no.go index fe0b016f..c2666a40 100644 --- a/service/wechatpayapiv3/refund.domestic.refunds.out_refund_no.go +++ b/service/wechatpayapiv3/refund.domestic.refunds.out_refund_no.go @@ -1,6 +1,7 @@ package wechatpayapiv3 import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -61,9 +62,9 @@ func newRefundDomesticRefundsOutRefundNoResult(result RefundDomesticRefundsOutRe } // RefundDomesticRefundsOutRefundNo 查询单笔退款API https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_10.shtml -func (c *Client) RefundDomesticRefundsOutRefundNo(outRefundNo string) *RefundDomesticRefundsOutRefundNoResult { +func (c *Client) RefundDomesticRefundsOutRefundNo(ctx context.Context, outRefundNo string) *RefundDomesticRefundsOutRefundNoResult { // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/refund/domestic/refunds/%s", outRefundNo), map[string]interface{}{}, http.MethodGet, true) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/refund/domestic/refunds/%s", outRefundNo), map[string]interface{}{}, http.MethodGet, true) if err != nil { return newRefundDomesticRefundsOutRefundNoResult(RefundDomesticRefundsOutRefundNoResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayapiv3/request.go b/service/wechatpayapiv3/request.go index a201112b..7541ec18 100644 --- a/service/wechatpayapiv3/request.go +++ b/service/wechatpayapiv3/request.go @@ -1,11 +1,13 @@ package wechatpayapiv3 import ( + "context" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" "net/http" ) -func (c *Client) request(url string, params map[string]interface{}, method string, commonParams bool) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string, commonParams bool) (gorequest.Response, error) { // 公共参数 if method == http.MethodPost { @@ -45,17 +47,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin } // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatpayopen/certificates.go b/service/wechatpayopen/certificates.go index 4c476220..302016bf 100644 --- a/service/wechatpayopen/certificates.go +++ b/service/wechatpayopen/certificates.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -34,9 +35,9 @@ func newCertificatesResult(result CertificatesResponse, body []byte, http gorequ // Certificates 获取平台证书列表 // https://pay.weixin.qq.com/wiki/doc/apiv3/apis/wechatpay5_1.shtml -func (c *Client) Certificates() *CertificatesResult { +func (c *Client) Certificates(ctx context.Context) *CertificatesResult { // 请求 - request, err := c.request(apiUrl+"/v3/certificates", map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/v3/certificates", map[string]interface{}{}, http.MethodGet) if err != nil { return newCertificatesResult(CertificatesResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/const.go b/service/wechatpayopen/const.go index d209f2d3..79e5fe12 100644 --- a/service/wechatpayopen/const.go +++ b/service/wechatpayopen/const.go @@ -12,9 +12,7 @@ const ( logTable = "wechatpayopen" ) -// SDK 相关信息 const ( - Version = "1.0.1" // SDK 版本 UserAgentFormat = "WechatPay-Go/%s (%s) GO/%s" // UserAgent中的信息 ) diff --git a/service/wechatpayopen/ecommerce.fund.balance.go b/service/wechatpayopen/ecommerce.fund.balance.go index 781e46ef..980f88e2 100644 --- a/service/wechatpayopen/ecommerce.fund.balance.go +++ b/service/wechatpayopen/ecommerce.fund.balance.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,11 +29,11 @@ func newEcommerceFundBalanceResult(result EcommerceFundBalanceResponse, body []b // EcommerceFundBalance 查询二级商户账户实时余额API // accountType 账户类型 BASIC:基本账户 OPERATION:运营账户 FEES:手续费账户 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_7_1.shtml -func (c *Client) EcommerceFundBalance(accountType string) *EcommerceFundBalanceResult { +func (c *Client) EcommerceFundBalance(ctx context.Context, accountType string) *EcommerceFundBalanceResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/ecommerce/fund/balance/%s?account_type=%s", c.config.SubMchId, accountType), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/ecommerce/fund/balance/%s?account_type=%s", c.config.SubMchId, accountType), params, http.MethodGet) if err != nil { return newEcommerceFundBalanceResult(EcommerceFundBalanceResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/ecommerce.fund.enddaybalance.go b/service/wechatpayopen/ecommerce.fund.enddaybalance.go index c2e887f0..361e57a3 100644 --- a/service/wechatpayopen/ecommerce.fund.enddaybalance.go +++ b/service/wechatpayopen/ecommerce.fund.enddaybalance.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newEcommerceFundEndDayBalanceResult(result EcommerceFundEndDayBalanceRespon // EcommerceFundEndDayBalance 查询二级商户账户日终余额API // date 日期 示例值:2019-08-17 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_7_2.shtml -func (c *Client) EcommerceFundEndDayBalance(date string) *EcommerceFundEndDayBalanceResult { +func (c *Client) EcommerceFundEndDayBalance(ctx context.Context, date string) *EcommerceFundEndDayBalanceResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/ecommerce/fund/enddaybalance/%s?date=%s", c.config.SubMchId, date), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/ecommerce/fund/enddaybalance/%s?date=%s", c.config.SubMchId, date), params, http.MethodGet) if err != nil { return newEcommerceFundEndDayBalanceResult(EcommerceFundEndDayBalanceResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/merchant.fund.balance.go b/service/wechatpayopen/merchant.fund.balance.go index 03b0c30d..c293eece 100644 --- a/service/wechatpayopen/merchant.fund.balance.go +++ b/service/wechatpayopen/merchant.fund.balance.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,11 +27,11 @@ func newMerchantFundBalanceResult(result MerchantFundBalanceResponse, body []byt // MerchantFundBalance 查询电商平台账户实时余额API // accountType 账户类型 BASIC:基本账户 OPERATION:运营账户 FEES:手续费账户 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_7_3.shtml -func (c *Client) MerchantFundBalance(accountType string) *MerchantFundBalanceResult { +func (c *Client) MerchantFundBalance(ctx context.Context, accountType string) *MerchantFundBalanceResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/merchant/fund/balance/%s", accountType), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/merchant/fund/balance/%s", accountType), params, http.MethodGet) if err != nil { return newMerchantFundBalanceResult(MerchantFundBalanceResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/merchant.fund.dayendbalance.go b/service/wechatpayopen/merchant.fund.dayendbalance.go index fa7eaff2..0566da36 100644 --- a/service/wechatpayopen/merchant.fund.dayendbalance.go +++ b/service/wechatpayopen/merchant.fund.dayendbalance.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newMerchantFundDayEndBalanceResult(result MerchantFundDayEndBalanceResponse // accountType 账户类型 BASIC:基本账户 OPERATION:运营账户 FEES:手续费账户 // date 日期 示例值:2019-08-17 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter7_7_4.shtml -func (c *Client) MerchantFundDayEndBalance(accountType, date string) *MerchantFundDayEndBalanceResult { +func (c *Client) MerchantFundDayEndBalance(ctx context.Context, accountType, date string) *MerchantFundDayEndBalanceResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/merchant/fund/dayendbalance/%s?date=%s", accountType, date), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/merchant/fund/dayendbalance/%s?date=%s", accountType, date), params, http.MethodGet) if err != nil { return newMerchantFundDayEndBalanceResult(MerchantFundDayEndBalanceResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/pay.jsapi.go b/service/wechatpayopen/pay.jsapi.go index 2ce76c32..6bb38a3b 100644 --- a/service/wechatpayopen/pay.jsapi.go +++ b/service/wechatpayopen/pay.jsapi.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "fmt" "github.com/dtapps/go-library/utils/gorandom" "time" @@ -22,7 +23,7 @@ type GetJsApiResult struct { } // GetJsApi JSAPI调起支付API https://pay.weixin.qq.com/wiki/doc/apiv3/apis/chapter3_1_4.shtml -func (c *Client) GetJsApi(param GetJsApi) (result GetJsApiResult, err error) { +func (c *Client) GetJsApi(ctx context.Context, param GetJsApi) (result GetJsApiResult, err error) { // sign params timeStamp := time.Now().Unix() diff --git a/service/wechatpayopen/pay.partner.transactions.h5.go b/service/wechatpayopen/pay.partner.transactions.h5.go index 1d80da78..4c548bba 100644 --- a/service/wechatpayopen/pay.partner.transactions.h5.go +++ b/service/wechatpayopen/pay.partner.transactions.h5.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -24,7 +25,7 @@ func newPayPartnerTransactionsH5Result(result PayPartnerTransactionsH5Response, // PayPartnerTransactionsH5 H5下单API // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_3_1.shtml -func (c *Client) PayPartnerTransactionsH5(notMustParams ...gorequest.Params) *PayPartnerTransactionsH5Result { +func (c *Client) PayPartnerTransactionsH5(ctx context.Context, notMustParams ...gorequest.Params) *PayPartnerTransactionsH5Result { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("sp_appid", c.config.SpAppid) // 服务商应用ID @@ -32,7 +33,7 @@ func (c *Client) PayPartnerTransactionsH5(notMustParams ...gorequest.Params) *Pa params.Set("sub_appid", c.config.SubAppid) // 子商户应用ID params.Set("sub_mchid", c.config.SubMchId) // 子商户号 // 请求 - request, err := c.request(apiUrl+"/v3/pay/partner/transactions/h5", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/v3/pay/partner/transactions/h5", params, http.MethodPost) if err != nil { return newPayPartnerTransactionsH5Result(PayPartnerTransactionsH5Response{}, request.ResponseBody, request, err, ApiError{}) } diff --git a/service/wechatpayopen/pay.partner.transactions.id.go b/service/wechatpayopen/pay.partner.transactions.id.go index b0a58a17..653590c1 100644 --- a/service/wechatpayopen/pay.partner.transactions.id.go +++ b/service/wechatpayopen/pay.partner.transactions.id.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -64,11 +65,11 @@ func newPayPartnerTransactionsIdResult(result PayPartnerTransactionsIdResponse, // PayPartnerTransactionsId 微信支付订单号查询 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_2.shtml -func (c *Client) PayPartnerTransactionsId(transactionId string) *PayPartnerTransactionsIdResult { +func (c *Client) PayPartnerTransactionsId(ctx context.Context, transactionId string) *PayPartnerTransactionsIdResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/id/%s?sp_mchid=%s&sub_mchid=%s", transactionId, c.config.SpMchId, c.config.SubMchId), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/id/%s?sp_mchid=%s&sub_mchid=%s", transactionId, c.config.SpMchId, c.config.SubMchId), params, http.MethodGet) if err != nil { return newPayPartnerTransactionsIdResult(PayPartnerTransactionsIdResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/pay.partner.transactions.jsapi.go b/service/wechatpayopen/pay.partner.transactions.jsapi.go index d21aef8a..0a44abce 100644 --- a/service/wechatpayopen/pay.partner.transactions.jsapi.go +++ b/service/wechatpayopen/pay.partner.transactions.jsapi.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -24,7 +25,7 @@ func newPayPartnerTransactionsJsapiResult(result PayPartnerTransactionsJsapiResp // PayPartnerTransactionsJsapi JSAPI下单 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_1.shtml -func (c *Client) PayPartnerTransactionsJsapi(notMustParams ...gorequest.Params) *PayPartnerTransactionsJsapiResult { +func (c *Client) PayPartnerTransactionsJsapi(ctx context.Context, notMustParams ...gorequest.Params) *PayPartnerTransactionsJsapiResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("sp_appid", c.config.SpAppid) // 服务商应用ID @@ -32,7 +33,7 @@ func (c *Client) PayPartnerTransactionsJsapi(notMustParams ...gorequest.Params) params.Set("sub_appid", c.config.SubAppid) // 子商户应用ID params.Set("sub_mchid", c.config.SubMchId) // 子商户号 // 请求 - request, err := c.request(apiUrl+"/v3/pay/partner/transactions/jsapi", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/v3/pay/partner/transactions/jsapi", params, http.MethodPost) if err != nil { return newPayPartnerTransactionsJsapiResult(PayPartnerTransactionsJsapiResponse{}, request.ResponseBody, request, err, ApiError{}) } diff --git a/service/wechatpayopen/pay.partner.transactions.out-trade-no.close.go b/service/wechatpayopen/pay.partner.transactions.out-trade-no.close.go index 1053e87e..834e3109 100644 --- a/service/wechatpayopen/pay.partner.transactions.out-trade-no.close.go +++ b/service/wechatpayopen/pay.partner.transactions.out-trade-no.close.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "fmt" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -18,13 +19,13 @@ func newPayPartnerTransactionsOutTradeNoCloseResult(body []byte, http gorequest. // PayPartnerTransactionsOutTradeNoClose 关闭订单API // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_3.shtml -func (c *Client) PayPartnerTransactionsOutTradeNoClose(outTradeNo string) *PayPartnerTransactionsOutTradeNoCloseResult { +func (c *Client) PayPartnerTransactionsOutTradeNoClose(ctx context.Context, outTradeNo string) *PayPartnerTransactionsOutTradeNoCloseResult { // 参数 params := gorequest.NewParams() params.Set("sp_mchid", c.config.SpMchId) // 服务商户号 params.Set("sub_mchid", c.config.SubMchId) // 子商户号 // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/out-trade-no/%s/close", outTradeNo), params, http.MethodPost) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/out-trade-no/%s/close", outTradeNo), params, http.MethodPost) if err != nil { return newPayPartnerTransactionsOutTradeNoCloseResult(request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/pay.partner.transactions.out-trade-no.go b/service/wechatpayopen/pay.partner.transactions.out-trade-no.go index 0b305c8c..4d416767 100644 --- a/service/wechatpayopen/pay.partner.transactions.out-trade-no.go +++ b/service/wechatpayopen/pay.partner.transactions.out-trade-no.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -68,11 +69,11 @@ func newPayPartnerTransactionsOutTradeNoResult(result PayPartnerTransactionsOutT // PayPartnerTransactionsOutTradeNo 商户订单号查询 // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_2.shtml -func (c *Client) PayPartnerTransactionsOutTradeNo(outTradeNo string) *PayPartnerTransactionsOutTradeNoResult { +func (c *Client) PayPartnerTransactionsOutTradeNo(ctx context.Context, outTradeNo string) *PayPartnerTransactionsOutTradeNoResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/out-trade-no/%s?sp_mchid=%s&sub_mchid=%s", outTradeNo, c.config.SpMchId, c.config.SubMchId), params, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf(apiUrl+"/v3/pay/partner/transactions/out-trade-no/%s?sp_mchid=%s&sub_mchid=%s", outTradeNo, c.config.SpMchId, c.config.SubMchId), params, http.MethodGet) if err != nil { return newPayPartnerTransactionsOutTradeNoResult(PayPartnerTransactionsOutTradeNoResponse{}, request.ResponseBody, request, err, ApiError{}) } diff --git a/service/wechatpayopen/refund.domestic.refunds.go b/service/wechatpayopen/refund.domestic.refunds.go index b432eb38..a91ae6aa 100644 --- a/service/wechatpayopen/refund.domestic.refunds.go +++ b/service/wechatpayopen/refund.domestic.refunds.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -62,12 +63,12 @@ func newRefundDomesticRefundsResult(result RefundDomesticRefundsResponse, body [ // RefundDomesticRefunds 申请退款API // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_9.shtml -func (c *Client) RefundDomesticRefunds(notMustParams ...gorequest.Params) *RefundDomesticRefundsResult { +func (c *Client) RefundDomesticRefunds(ctx context.Context, notMustParams ...gorequest.Params) *RefundDomesticRefundsResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("sub_mchid", c.config.SubMchId) // 子商户号 // 请求 - request, err := c.request(apiUrl+"/v3/refund/domestic/refunds", params, http.MethodPost) + request, err := c.request(ctx, apiUrl+"/v3/refund/domestic/refunds", params, http.MethodPost) if err != nil { return newRefundDomesticRefundsResult(RefundDomesticRefundsResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/refund.domestic.refunds.out_refund_no.go b/service/wechatpayopen/refund.domestic.refunds.out_refund_no.go index 345a01d7..26ca6ae2 100644 --- a/service/wechatpayopen/refund.domestic.refunds.out_refund_no.go +++ b/service/wechatpayopen/refund.domestic.refunds.out_refund_no.go @@ -1,6 +1,7 @@ package wechatpayopen import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net/http" @@ -62,11 +63,11 @@ func newRefundDomesticRefundsOutRefundNoResult(result RefundDomesticRefundsOutRe // RefundDomesticRefundsOutRefundNo 查询单笔退款API // https://pay.weixin.qq.com/wiki/doc/apiv3_partner/apis/chapter4_5_9.shtml -func (c *Client) RefundDomesticRefundsOutRefundNo(outRefundNo string) *RefundDomesticRefundsOutRefundNoResult { +func (c *Client) RefundDomesticRefundsOutRefundNo(ctx context.Context, outRefundNo string) *RefundDomesticRefundsOutRefundNoResult { // 参数 params := gorequest.NewParams() // 请求 - request, err := c.request(apiUrl+"/v3/refund/domestic/refunds/"+outRefundNo+"?sub_mchid="+c.config.SubMchId, params, http.MethodGet) + request, err := c.request(ctx, apiUrl+"/v3/refund/domestic/refunds/"+outRefundNo+"?sub_mchid="+c.config.SubMchId, params, http.MethodGet) if err != nil { return newRefundDomesticRefundsOutRefundNoResult(RefundDomesticRefundsOutRefundNoResponse{}, request.ResponseBody, request, err) } diff --git a/service/wechatpayopen/request.go b/service/wechatpayopen/request.go index d9a1f1fd..338965ab 100644 --- a/service/wechatpayopen/request.go +++ b/service/wechatpayopen/request.go @@ -1,8 +1,12 @@ package wechatpayopen -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 认证 authorization, err := c.authorization(method, params, url) @@ -31,17 +35,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetHeader("Accept-Language", "zh-CN") // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatqy/cgi-bin.gettoken.go b/service/wechatqy/cgi-bin.gettoken.go index a6ca0951..49f3098b 100644 --- a/service/wechatqy/cgi-bin.gettoken.go +++ b/service/wechatqy/cgi-bin.gettoken.go @@ -1,6 +1,7 @@ package wechatqy import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -27,11 +28,11 @@ func newCgiBinGetTokenResult(result CgiBinGetTokenResponse, body []byte, http go // CgiBinGetToken 获取access_token // https://open.work.weixin.qq.com/api/doc/90000/90135/91039 -func (c *Client) CgiBinGetToken(notMustParams ...gorequest.Params) *CgiBinGetTokenResult { +func (c *Client) CgiBinGetToken(ctx context.Context, notMustParams ...gorequest.Params) *CgiBinGetTokenResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/cgi-bin/gettoken?corpid=%s&corpsecret=%s", c.GetAppId(), c.GetSecret()), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/cgi-bin/gettoken?corpid=%s&corpsecret=%s", c.GetAppId(), c.GetSecret()), params, http.MethodGet) // 定义 var response CgiBinGetTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatqy/cgi-bin.user.getuserinfo.go b/service/wechatqy/cgi-bin.user.getuserinfo.go index a779102c..473f3ade 100644 --- a/service/wechatqy/cgi-bin.user.getuserinfo.go +++ b/service/wechatqy/cgi-bin.user.getuserinfo.go @@ -1,6 +1,7 @@ package wechatqy import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -29,11 +30,11 @@ func newCgiBinUserGetUserInfoResult(result CgiBinUserGetUserInfoResponse, body [ // CgiBinUserGetUserInfo 获取访问用户身份 // https://open.work.weixin.qq.com/api/doc/90000/90135/91023 -func (c *Client) CgiBinUserGetUserInfo(code, accessToken string) *CgiBinUserGetUserInfoResult { +func (c *Client) CgiBinUserGetUserInfo(ctx context.Context, code, accessToken string) *CgiBinUserGetUserInfoResult { // 参数 params := gorequest.NewParamsWith() // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/cgi-bin/user/getuserinfo?access_token=%s&code=%s", accessToken, code), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/cgi-bin/user/getuserinfo?access_token=%s&code=%s", accessToken, code), params, http.MethodGet) // 定义 var response CgiBinUserGetUserInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatqy/connect.oauth2.authorize.go b/service/wechatqy/connect.oauth2.authorize.go index 29ac490c..aad13a87 100644 --- a/service/wechatqy/connect.oauth2.authorize.go +++ b/service/wechatqy/connect.oauth2.authorize.go @@ -1,11 +1,12 @@ package wechatqy import ( + "context" "fmt" ) // ConnectOauth2Authorize 构造网页授权链接 // https://work.weixin.qq.com/api/doc/90000/90135/91022 -func (c *Client) ConnectOauth2Authorize() string { +func (c *Client) ConnectOauth2Authorize(ctx context.Context) string { return fmt.Sprintf("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect", c.GetAppId(), c.GetRedirectUri()) } diff --git a/service/wechatqy/request.go b/service/wechatqy/request.go index 4aaa6b84..6046cc38 100644 --- a/service/wechatqy/request.go +++ b/service/wechatqy/request.go @@ -1,8 +1,12 @@ package wechatqy -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -19,17 +23,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wechatqy/webhook.send.go b/service/wechatqy/webhook.send.go index e7ab7e6b..e70fb143 100644 --- a/service/wechatqy/webhook.send.go +++ b/service/wechatqy/webhook.send.go @@ -1,6 +1,7 @@ package wechatqy import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,11 +29,11 @@ func newWebhookSendResult(result WebhookSendResponse, body []byte, http goreques // WebhookSend 发送应用消息 // https://developer.work.weixin.qq.com/document/path/90372 -func (c *Client) WebhookSend(notMustParams ...gorequest.Params) *WebhookSendResult { +func (c *Client) WebhookSend(ctx context.Context, notMustParams ...gorequest.Params) *WebhookSendResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/cgi-bin/webhook/send?key=%s&type=%s", c.GetKey(), "text"), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/cgi-bin/webhook/send?key=%s&type=%s", c.GetKey(), "text"), params, http.MethodPost) // 定义 var response WebhookSendResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatqy/wwopen.sso.qrConnect.go b/service/wechatqy/wwopen.sso.qrConnect.go index dbfd3078..404729e6 100644 --- a/service/wechatqy/wwopen.sso.qrConnect.go +++ b/service/wechatqy/wwopen.sso.qrConnect.go @@ -1,11 +1,12 @@ package wechatqy import ( + "context" "fmt" ) // WwOpenSsoQrConnect 构造独立窗口登录二维码 // https://open.work.weixin.qq.com/api/doc/90000/90135/91019 -func (c *Client) WwOpenSsoQrConnect() string { +func (c *Client) WwOpenSsoQrConnect(ctx context.Context) string { return fmt.Sprintf("https://open.work.weixin.qq.com/wwopen/sso/qrConnect?appid=%s&agentid=%d&redirect_uri=%s&state=STATE&lang=zh", c.GetAppId(), c.GetAgentId(), c.GetRedirectUri()) } diff --git a/service/wechatunion/cgi-bin.token.monitor.go b/service/wechatunion/cgi-bin.token.monitor.go index 547ec0c7..5e5ea834 100644 --- a/service/wechatunion/cgi-bin.token.monitor.go +++ b/service/wechatunion/cgi-bin.token.monitor.go @@ -6,14 +6,14 @@ import ( "time" ) -func (c *Client) GetAccessTokenMonitor() (string, error) { +func (c *Client) GetAccessTokenMonitor(ctx context.Context) (string, error) { if c.config.RedisClient.Db == nil { return "", errors.New("驱动没有初始化") } - result := c.GetCallBackIp() + result := c.GetCallBackIp(ctx) if len(result.Result.IpList) <= 0 { - token := c.CgiBinToken() - c.config.RedisClient.Db.Set(context.Background(), c.getAccessTokenCacheKeyName(), token.Result.AccessToken, time.Second*7000) + token := c.CgiBinToken(ctx) + c.config.RedisClient.Set(ctx, c.getAccessTokenCacheKeyName(), token.Result.AccessToken, time.Second*7000) return token.Result.AccessToken, nil } return c.config.AccessToken, nil diff --git a/service/wechatunion/cgi-bin.token.rdb.go b/service/wechatunion/cgi-bin.token.rdb.go index 4f646852..279cf717 100644 --- a/service/wechatunion/cgi-bin.token.rdb.go +++ b/service/wechatunion/cgi-bin.token.rdb.go @@ -1,17 +1,18 @@ package wechatunion import ( + "context" "fmt" "time" ) -func (c *Client) GetAccessToken() string { +func (c *Client) GetAccessToken(ctx context.Context) string { if c.config.RedisClient.Db == nil { return c.config.AccessToken } newCache := c.config.RedisClient.NewSimpleStringCache(c.config.RedisClient.NewStringOperation(), time.Second*7000) newCache.DBGetter = func() string { - token := c.CgiBinToken() + token := c.CgiBinToken(ctx) return token.Result.AccessToken } return newCache.GetCache(c.getAccessTokenCacheKeyName()) diff --git a/service/wechatunion/cgi_bin.token.go b/service/wechatunion/cgi_bin.token.go index 8d1c79e6..4e8a3604 100644 --- a/service/wechatunion/cgi_bin.token.go +++ b/service/wechatunion/cgi_bin.token.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -28,9 +29,9 @@ func newCgiBinTokenResult(result CgiBinTokenResponse, byte []byte, http goreques // CgiBinToken // 接口调用凭证 // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html -func (c *Client) CgiBinToken() *CgiBinTokenResult { +func (c *Client) CgiBinToken(ctx context.Context) *CgiBinTokenResult { // 请求 - request, err := c.request(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.getAppId(), c.getAppSecret()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", c.getAppId(), c.getAppSecret()), map[string]interface{}{}, http.MethodGet) // 定义 var response CgiBinTokenResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/get.go b/service/wechatunion/get.go index 8edda1c1..cb9d9386 100644 --- a/service/wechatunion/get.go +++ b/service/wechatunion/get.go @@ -1,5 +1,7 @@ package wechatunion +import "context" + func (c *Client) getAppId() string { return c.config.AppId } @@ -8,8 +10,8 @@ func (c *Client) getAppSecret() string { return c.config.AppSecret } -func (c *Client) getAccessToken() string { - c.config.AccessToken = c.GetAccessToken() +func (c *Client) getAccessToken(ctx context.Context) string { + c.config.AccessToken = c.GetAccessToken(ctx) return c.config.AccessToken } diff --git a/service/wechatunion/getcallbackip.go b/service/wechatunion/getcallbackip.go index 0ca2b22b..737572bd 100644 --- a/service/wechatunion/getcallbackip.go +++ b/service/wechatunion/getcallbackip.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -24,9 +25,9 @@ func newGetCallBackIpResult(result GetCallBackIpResponse, byte []byte, http gore // GetCallBackIp 获取微信callback IP地址 // callback IP即微信调用开发者服务器所使用的出口IP。 // https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_the_WeChat_server_IP_address.html#2.%20%E8%8E%B7%E5%8F%96%E5%BE%AE%E4%BF%A1callback%20IP%E5%9C%B0%E5%9D%80 -func (c *Client) GetCallBackIp() *GetCallBackIpResult { +func (c *Client) GetCallBackIp(ctx context.Context) *GetCallBackIpResult { // 请求 - request, err := c.request(fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken()), map[string]interface{}{}, "GET") + request, err := c.request(ctx, fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=%s", c.getAccessToken(ctx)), map[string]interface{}{}, "GET") // 定义 var response GetCallBackIpResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/order.go b/service/wechatunion/order.go index 942c1b08..9c1a8e75 100644 --- a/service/wechatunion/order.go +++ b/service/wechatunion/order.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "errors" "github.com/dtapps/go-library/utils/gorequest" ) @@ -51,8 +52,8 @@ type OrderSearchResult struct { } // OrderSearch 根据订单支付时间、订单分佣状态拉取订单详情 https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/order/order-info.html -func (c *Client) OrderSearch(notMustParams ...gorequest.Params) (result OrderSearchResult, err error) { - if len(c.getAccessToken()) <= 0 { +func (c *Client) OrderSearch(ctx context.Context, notMustParams ...gorequest.Params) (result OrderSearchResult, err error) { + if len(c.getAccessToken(ctx)) <= 0 { return result, errors.New("调用凭证异常") } diff --git a/service/wechatunion/promoter.order.info.go b/service/wechatunion/promoter.order.info.go index 288f04c8..2afdf0e5 100644 --- a/service/wechatunion/promoter.order.info.go +++ b/service/wechatunion/promoter.order.info.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -55,7 +56,7 @@ func newPromoterOrderInfoResult(result PromoterOrderInfoResponse, body []byte, h // PromoterOrderInfo 根据订单ID查询订单详情 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/order/order-info.html#_1-%E6%A0%B9%E6%8D%AE%E8%AE%A2%E5%8D%95ID%E6%9F%A5%E8%AF%A2%E8%AE%A2%E5%8D%95%E8%AF%A6%E6%83%85 -func (c *Client) PromoterOrderInfo(orderId ...string) *PromoterOrderInfoResult { +func (c *Client) PromoterOrderInfo(ctx context.Context, orderId ...string) *PromoterOrderInfoResult { // 参数 params := gorequest.NewParamsWith() var orderIdList []any @@ -64,7 +65,7 @@ func (c *Client) PromoterOrderInfo(orderId ...string) *PromoterOrderInfoResult { } params.Set("orderIdList", orderIdList) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/order/info?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/order/info?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response PromoterOrderInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.order.search.go b/service/wechatunion/promoter.order.search.go index e4b1f845..4889e1b9 100644 --- a/service/wechatunion/promoter.order.search.go +++ b/service/wechatunion/promoter.order.search.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -57,11 +58,11 @@ func newPromoterOrderSearchResult(result PromoterOrderSearchResponse, body []byt // PromoterOrderSearch 根据订单支付时间、订单分佣状态拉取订单详情 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/order/order-info.html#_2-%E6%A0%B9%E6%8D%AE%E8%AE%A2%E5%8D%95%E6%94%AF%E4%BB%98%E6%97%B6%E9%97%B4%E3%80%81%E8%AE%A2%E5%8D%95%E5%88%86%E4%BD%A3%E7%8A%B6%E6%80%81%E6%8B%89%E5%8F%96%E8%AE%A2%E5%8D%95%E8%AF%A6%E6%83%85 -func (c *Client) PromoterOrderSearch(notMustParams ...gorequest.Params) *PromoterOrderSearchResult { +func (c *Client) PromoterOrderSearch(ctx context.Context, notMustParams ...gorequest.Params) *PromoterOrderSearchResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/order/search?access_token=%s", c.getAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/order/search?access_token=%s", c.getAccessToken(ctx)), params, http.MethodGet) // 定义 var response PromoterOrderSearchResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.product.category.go b/service/wechatunion/promoter.product.category.go index a2dce5ac..2728f7f1 100644 --- a/service/wechatunion/promoter.product.category.go +++ b/service/wechatunion/promoter.product.category.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -29,9 +30,9 @@ func newPromoterProductCategoryResult(result PromoterProductCategoryResponse, bo // PromoterProductCategory 获取联盟商品类目列表及类目ID // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/product/category.html#_1-%E8%8E%B7%E5%8F%96%E8%81%94%E7%9B%9F%E5%95%86%E5%93%81%E7%B1%BB%E7%9B%AE%E5%88%97%E8%A1%A8%E5%8F%8A%E7%B1%BB%E7%9B%AEID -func (c *Client) PromoterProductCategory() *PromoterProductCategoryResult { +func (c *Client) PromoterProductCategory(ctx context.Context) *PromoterProductCategoryResult { // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/product/category?access_token=%s", c.getAccessToken()), map[string]interface{}{}, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/product/category?access_token=%s", c.getAccessToken(ctx)), map[string]interface{}{}, http.MethodGet) // 定义 var response PromoterProductCategoryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.product.generate.go b/service/wechatunion/promoter.product.generate.go index b3f98c1d..4d8d0c45 100644 --- a/service/wechatunion/promoter.product.generate.go +++ b/service/wechatunion/promoter.product.generate.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -55,12 +56,12 @@ func newPromoterProductGenerateResult(result PromoterProductGenerateResponse, bo // PromoterProductGenerate 获取商品推广素材 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/product/category.html#_4-%E8%8E%B7%E5%8F%96%E5%95%86%E5%93%81%E6%8E%A8%E5%B9%BF%E7%B4%A0%E6%9D%90 -func (c *Client) PromoterProductGenerate(notMustParams ...gorequest.Params) *PromoterProductGenerateResult { +func (c *Client) PromoterProductGenerate(ctx context.Context, notMustParams ...gorequest.Params) *PromoterProductGenerateResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("pid", c.getPid()) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/product/generate?access_token=%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/product/generate?access_token=%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response PromoterProductGenerateResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.product.list.go b/service/wechatunion/promoter.product.list.go index 34afbec1..e95fa4ca 100644 --- a/service/wechatunion/promoter.product.list.go +++ b/service/wechatunion/promoter.product.list.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -139,11 +140,11 @@ func newPromoterProductListResult(result PromoterProductListResponse, body []byt // PromoterProductList 查询全量商品 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/product/category.html#_2-%E6%9F%A5%E8%AF%A2%E5%85%A8%E9%87%8F%E5%95%86%E5%93%81 -func (c *Client) PromoterProductList(notMustParams ...gorequest.Params) *PromoterProductListResult { +func (c *Client) PromoterProductList(ctx context.Context, notMustParams ...gorequest.Params) *PromoterProductListResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/product/list?access_token=%s", c.getAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/product/list?access_token=%s", c.getAccessToken(ctx)), params, http.MethodGet) // 定义 var response PromoterProductListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.product.select.go b/service/wechatunion/promoter.product.select.go index 51d9b449..8854e410 100644 --- a/service/wechatunion/promoter.product.select.go +++ b/service/wechatunion/promoter.product.select.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -140,11 +141,11 @@ func newPromoterProductSelectResult(result PromoterProductSelectResponse, body [ // 查询联盟精选商品 // 支持开发者根据多种筛选条件获取联盟精选的商品列表及详情,筛选条件包括商品价格、商品佣金、商品累计销量、佣金比例、是否含有联盟券、配送方式、发货地区 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/product/category.html#3.%E6%9F%A5%E8%AF%A2%E8%81%94%E7%9B%9F%E7%B2%BE%E9%80%89%E5%95%86%E5%93%81 -func (c *Client) PromoterProductSelect(notMustParams ...gorequest.Params) *PromoterProductSelectResult { +func (c *Client) PromoterProductSelect(ctx context.Context, notMustParams ...gorequest.Params) *PromoterProductSelectResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/product/select?access_token=%s", c.getAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/product/select?access_token=%s", c.getAccessToken(ctx)), params, http.MethodGet) // 定义 var response PromoterProductSelectResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.promotion.add.go b/service/wechatunion/promoter.promotion.add.go index 7563bb5f..f5e258bc 100644 --- a/service/wechatunion/promoter.promotion.add.go +++ b/service/wechatunion/promoter.promotion.add.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -26,12 +27,12 @@ func newPromotionAddResult(result PromotionAddResponse, body []byte, http gorequ // PromotionAdd 添加推广位 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/promotion.html#_1-%E6%B7%BB%E5%8A%A0%E6%8E%A8%E5%B9%BF%E4%BD%8D -func (c *Client) PromotionAdd(promotionSourceName string) *PromotionAddResult { +func (c *Client) PromotionAdd(ctx context.Context, promotionSourceName string) *PromotionAddResult { // 参数 params := gorequest.NewParams() params.Set("promotionSourceName", promotionSourceName) // 推广位名称 // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/promotion/add?access_token%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/promotion/add?access_token%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response PromotionAddResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.promotion.del.go b/service/wechatunion/promoter.promotion.del.go index 53029942..1441b808 100644 --- a/service/wechatunion/promoter.promotion.del.go +++ b/service/wechatunion/promoter.promotion.del.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,13 +26,13 @@ func newPromotionDelResult(result PromotionDelResponse, body []byte, http gorequ // PromotionDel 删除某个推广位 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/promotion.html#_3-%E7%BC%96%E8%BE%91%E6%8E%A8%E5%B9%BF%E4%BD%8D -func (c *Client) PromotionDel(promotionSourcePid, promotionSourceName string) *PromotionDelResult { +func (c *Client) PromotionDel(ctx context.Context, promotionSourcePid, promotionSourceName string) *PromotionDelResult { // 参数 params := gorequest.NewParams() params.Set("promotionSourcePid", promotionSourcePid) // 推广位PID params.Set("promotionSourceName", promotionSourceName) // 推广位名称 // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/promotion/del?access_token%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/promotion/del?access_token%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response PromotionDelResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.promotion.list.go b/service/wechatunion/promoter.promotion.list.go index 2d32b7f9..f146e21c 100644 --- a/service/wechatunion/promoter.promotion.list.go +++ b/service/wechatunion/promoter.promotion.list.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -33,13 +34,13 @@ func newPromotionListResult(result PromotionListResponse, body []byte, http gore // PromotionList 获取推广位列表 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/promotion.html#_4-%E8%8E%B7%E5%8F%96%E6%8E%A8%E5%B9%BF%E4%BD%8D%E5%88%97%E8%A1%A8 -func (c *Client) PromotionList(start int, limit int) *PromotionListResult { +func (c *Client) PromotionList(ctx context.Context, start int, limit int) *PromotionListResult { // 参数 params := gorequest.NewParams() params.Set("start", start) // 偏移 params.Set("limit", limit) // 每页条数 // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/promotion/list?access_token%s", c.getAccessToken()), params, http.MethodGet) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/promotion/list?access_token%s", c.getAccessToken(ctx)), params, http.MethodGet) // 定义 var response PromotionListResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/promoter.promotion.upd.go b/service/wechatunion/promoter.promotion.upd.go index 9db737cc..27694615 100644 --- a/service/wechatunion/promoter.promotion.upd.go +++ b/service/wechatunion/promoter.promotion.upd.go @@ -1,6 +1,7 @@ package wechatunion import ( + "context" "encoding/json" "fmt" "github.com/dtapps/go-library/utils/gorequest" @@ -25,11 +26,11 @@ func newPromotionUpdResult(result PromotionUpdResponse, body []byte, http gorequ // PromotionUpd 编辑推广位 // https://developers.weixin.qq.com/doc/ministore/union/access-guidelines/promoter/api/promotion.html#_3-%E7%BC%96%E8%BE%91%E6%8E%A8%E5%B9%BF%E4%BD%8D -func (c *Client) PromotionUpd(notMustParams ...gorequest.Params) *PromotionUpdResult { +func (c *Client) PromotionUpd(ctx context.Context, notMustParams ...gorequest.Params) *PromotionUpdResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+fmt.Sprintf("/promoter/promotion/upd?access_token%s", c.getAccessToken()), params, http.MethodPost) + request, err := c.request(ctx, apiUrl+fmt.Sprintf("/promoter/promotion/upd?access_token%s", c.getAccessToken(ctx)), params, http.MethodPost) // 定义 var response PromotionUpdResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wechatunion/request.go b/service/wechatunion/request.go index 127f3f39..5da1d4e3 100644 --- a/service/wechatunion/request.go +++ b/service/wechatunion/request.go @@ -1,9 +1,13 @@ package wechatunion -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) // 请求 -func (c *Client) request(url string, params map[string]interface{}, method string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}, method string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -21,17 +25,17 @@ func (c *Client) request(url string, params map[string]interface{}, method strin client.SetParams(params) // 发起请求 - request, err := client.Request() + request, err := client.Request(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/weishi/api.go b/service/weishi/api.go index 9765fda9..d1e7016e 100644 --- a/service/weishi/api.go +++ b/service/weishi/api.go @@ -1,6 +1,7 @@ package weishi import ( + "context" "encoding/json" "errors" "github.com/dtapps/go-library/utils/gorequest" @@ -1053,7 +1054,7 @@ func newAnalysisResult(result AnalysisResponse, body []byte, http gorequest.Resp } // Analysis 微视解析 -func (c *Client) Analysis(content string) *AnalysisResult { +func (c *Client) Analysis(ctx context.Context, content string) *AnalysisResult { // 提取url var url string @@ -1081,7 +1082,7 @@ func (c *Client) Analysis(content string) *AnalysisResult { feedid = regexp.MustCompile("id=(.*?)&").FindStringSubmatch(url)[1] } - request, err := c.request("https://h5.qzone.qq.com/webapp/json/weishi/WSH5GetPlayPage?feedid=" + feedid) + request, err := c.request(ctx, "https://h5.qzone.qq.com/webapp/json/weishi/WSH5GetPlayPage?feedid="+feedid) // 定义 var response AnalysisResponse diff --git a/service/weishi/request.go b/service/weishi/request.go index 5c676065..485fa68a 100644 --- a/service/weishi/request.go +++ b/service/weishi/request.go @@ -1,8 +1,12 @@ package weishi -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/gorequest" +) -func (c *Client) request(url string) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string) (gorequest.Response, error) { // 创建请求 client := c.client @@ -14,17 +18,17 @@ func (c *Client) request(url string) (gorequest.Response, error) { client.SetUserAgent(c.ua) // 发起请求 - request, err := client.Get() + request, err := client.Get(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wikeyun/client.go b/service/wikeyun/client.go index db7ae086..2bdc30ec 100644 --- a/service/wikeyun/client.go +++ b/service/wikeyun/client.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "github.com/dtapps/go-library/utils/dorm" "github.com/dtapps/go-library/utils/goip" "github.com/dtapps/go-library/utils/golog" @@ -51,7 +52,7 @@ func NewClient(config *ConfigClient) (*Client, error) { } } - xip := goip.GetOutsideIp() + xip := goip.GetOutsideIp(context.Background()) if xip != "" && xip != "0.0.0.0" { c.clientIp = xip } diff --git a/service/wikeyun/request.go b/service/wikeyun/request.go index c1b3e045..76e0b150 100644 --- a/service/wikeyun/request.go +++ b/service/wikeyun/request.go @@ -1,12 +1,14 @@ package wikeyun import ( + "context" "fmt" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/gorequest" ) // 请求接口 -func (c *Client) request(url string, params map[string]interface{}) (gorequest.Response, error) { +func (c *Client) request(ctx context.Context, url string, params map[string]interface{}) (gorequest.Response, error) { // 签名 sign := c.sign(params) @@ -24,17 +26,17 @@ func (c *Client) request(url string, params map[string]interface{}) (gorequest.R client.SetParams(params) // 发起请求 - request, err := client.Post() + request, err := client.Post(ctx) if err != nil { return gorequest.Response{}, err } // 日志 if c.config.PgsqlDb != nil { - go c.log.GormMiddleware(request) + go c.log.GormMiddleware(ctx, request, go_library.Version()) } if c.config.MongoDb != nil { - go c.log.MongoMiddleware(request) + go c.log.MongoMiddleware(ctx, request, go_library.Version()) } return request, err diff --git a/service/wikeyun/rest.oil.add_card.go b/service/wikeyun/rest.oil.add_card.go index f5cf33ce..93d839b5 100644 --- a/service/wikeyun/rest.oil.add_card.go +++ b/service/wikeyun/rest.oil.add_card.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilCardAdd 添加充值卡 -func (c *Client) RestOilCardAdd(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilCardAdd(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/addCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/addCard", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.oil.card_info.go b/service/wikeyun/rest.oil.card_info.go index 55867b31..452a37fb 100644 --- a/service/wikeyun/rest.oil.card_info.go +++ b/service/wikeyun/rest.oil.card_info.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilCardInfo 油卡详情 -func (c *Client) RestOilCardInfo(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilCardInfo(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/cardInfo", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/cardInfo", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.oil.del_card.go b/service/wikeyun/rest.oil.del_card.go index 046c793e..345cbef6 100644 --- a/service/wikeyun/rest.oil.del_card.go +++ b/service/wikeyun/rest.oil.del_card.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilCardDel 油卡删除 -func (c *Client) RestOilCardDel(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilCardDel(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/delCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/delCard", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.oil.push_order.go b/service/wikeyun/rest.oil.push_order.go index cd212e97..bb789f9d 100644 --- a/service/wikeyun/rest.oil.push_order.go +++ b/service/wikeyun/rest.oil.push_order.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilOrderPush 充值下单 -func (c *Client) RestOilOrderPush(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilOrderPush(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/pushOrder", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/pushOrder", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.oil.query.go b/service/wikeyun/rest.oil.query.go index a237a6e5..b81535c9 100644 --- a/service/wikeyun/rest.oil.query.go +++ b/service/wikeyun/rest.oil.query.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilOrderQuery 订单查询 -func (c *Client) RestOilOrderQuery(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilOrderQuery(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/query", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/query", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.oiledit_card.go b/service/wikeyun/rest.oiledit_card.go index 6a363c58..83fba51c 100644 --- a/service/wikeyun/rest.oiledit_card.go +++ b/service/wikeyun/rest.oiledit_card.go @@ -1,12 +1,15 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestOilCardEdit 编辑充值卡 -func (c *Client) RestOilCardEdit(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestOilCardEdit(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Oil/editCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Oil/editCard", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.power.add_card.go b/service/wikeyun/rest.power.add_card.go index eb3a4319..c561c885 100644 --- a/service/wikeyun/rest.power.add_card.go +++ b/service/wikeyun/rest.power.add_card.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -34,12 +35,12 @@ func newRestPowerAddCardResult(result RestPowerAddCardResponse, body []byte, htt // RestPowerAddCard 添加电费充值卡 // https://open.wikeyun.cn/#/apiDocument/9/document/326 -func (c *Client) RestPowerAddCard(notMustParams ...gorequest.Params) *RestPowerAddCardResult { +func (c *Client) RestPowerAddCard(ctx context.Context, notMustParams ...gorequest.Params) *RestPowerAddCardResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("store_id", c.config.StoreId) // 店铺ID // 请求 - request, err := c.request(apiUrl+"/rest/Power/addCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/addCard", params) // 定义 var response RestPowerAddCardResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.power.cancel.go b/service/wikeyun/rest.power.cancel.go index 28855bf0..2cba65ec 100644 --- a/service/wikeyun/rest.power.cancel.go +++ b/service/wikeyun/rest.power.cancel.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -24,13 +25,13 @@ func newRestPowerCancelResult(result RestPowerCancelResponse, body []byte, http // RestPowerCancel 电费订单取消 // https://open.wikeyun.cn/#/apiDocument/9/document/323 -func (c *Client) RestPowerCancel(orderNumber string) *RestPowerCancelResult { +func (c *Client) RestPowerCancel(ctx context.Context, orderNumber string) *RestPowerCancelResult { // 参数 param := gorequest.NewParams() param.Set("order_number", orderNumber) // 取消的单号,多个用英文逗号隔开 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Power/cancel", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/cancel", params) // 定义 var response RestPowerCancelResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.power.card_info.go b/service/wikeyun/rest.power.card_info.go index bea7392b..7d70161f 100644 --- a/service/wikeyun/rest.power.card_info.go +++ b/service/wikeyun/rest.power.card_info.go @@ -1,13 +1,16 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // PowerCardInfo 电费充值卡详情 // https://open.wikeyun.cn/#/apiDocument/9/document/333 -func (c *Client) PowerCardInfo(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) PowerCardInfo(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Power/cardInfo", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/cardInfo", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.power.del_card.go b/service/wikeyun/rest.power.del_card.go index 2cc1320c..855f2793 100644 --- a/service/wikeyun/rest.power.del_card.go +++ b/service/wikeyun/rest.power.del_card.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -25,13 +26,13 @@ func newRestPowerDelCardResult(result RestPowerDelCardResponse, body []byte, htt // RestPowerDelCard 删除电费充值卡 // https://open.wikeyun.cn/#/apiDocument/9/document/330 -func (c *Client) RestPowerDelCard(cardId string) *RestPowerDelCardResult { +func (c *Client) RestPowerDelCard(ctx context.Context, cardId string) *RestPowerDelCardResult { // 参数 param := gorequest.NewParams() param.Set("card_id", cardId) params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Power/delCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/delCard", params) // 定义 var response RestPowerDelCardResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.power.edit_card.go b/service/wikeyun/rest.power.edit_card.go index 61ca5e3f..36d6fbed 100644 --- a/service/wikeyun/rest.power.edit_card.go +++ b/service/wikeyun/rest.power.edit_card.go @@ -1,13 +1,16 @@ package wikeyun -import "github.com/dtapps/go-library/utils/gorequest" +import ( + "context" + "github.com/dtapps/go-library/utils/gorequest" +) // RestPowerEditCard 编辑电费充值卡 // https://open.wikeyun.cn/#/apiDocument/9/document/329 -func (c *Client) RestPowerEditCard(notMustParams ...gorequest.Params) (body []byte, err error) { +func (c *Client) RestPowerEditCard(ctx context.Context, notMustParams ...gorequest.Params) (body []byte, err error) { // 参数 params := gorequest.NewParamsWith(notMustParams...) // 请求 - request, err := c.request(apiUrl+"/rest/Power/editCard", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/editCard", params) return request.ResponseBody, err } diff --git a/service/wikeyun/rest.power.push_order.go b/service/wikeyun/rest.power.push_order.go index 6f0954a1..e9fbbc79 100644 --- a/service/wikeyun/rest.power.push_order.go +++ b/service/wikeyun/rest.power.push_order.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -27,12 +28,12 @@ func newRestPowerPushOrderResult(result RestPowerPushOrderResponse, body []byte, // RestPowerPushOrder 电费充值API // https://open.wikeyun.cn/#/apiDocument/9/document/311 -func (c *Client) RestPowerPushOrder(notMustParams ...gorequest.Params) *RestPowerPushOrderResult { +func (c *Client) RestPowerPushOrder(ctx context.Context, notMustParams ...gorequest.Params) *RestPowerPushOrderResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("store_id", c.config.StoreId) // 店铺ID // 请求 - request, err := c.request(apiUrl+"/rest/Power/pushOrder", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/pushOrder", params) // 定义 var response RestPowerPushOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.power.query.go b/service/wikeyun/rest.power.query.go index a295e55c..b2ad737b 100644 --- a/service/wikeyun/rest.power.query.go +++ b/service/wikeyun/rest.power.query.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -10,13 +11,14 @@ type RestPowerQueryResponse struct { Msg string `json:"msg"` Time string `json:"time"` Data struct { - OrderNumber string `json:"order_number"` - OrderNo string `json:"order_no"` - CardId string `json:"card_id"` - Amount int `json:"amount"` - CostPrice string `json:"cost_price"` + Id uint `json:"id"` Fanli string `json:"fanli"` + Amount int64 `json:"amount"` Status int `json:"status"` + CardId string `json:"card_id"` + OrderNo string `json:"order_no"` + CostPrice string `json:"cost_price"` + OrderNumber string `json:"order_number"` ArrivedAmount int64 `json:"arrived_amount"` } `json:"data"` } @@ -34,13 +36,13 @@ func newRestPowerQueryResult(result RestPowerQueryResponse, body []byte, http go // RestPowerQuery 电费订单查询 // https://open.wikeyun.cn/#/apiDocument/9/document/313 -func (c *Client) RestPowerQuery(orderNumber string) *RestPowerQueryResult { +func (c *Client) RestPowerQuery(ctx context.Context, orderNumber string) *RestPowerQueryResult { // 参数 param := gorequest.NewParams() param.Set("order_number", orderNumber) // 平台单号 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Power/query", params) + request, err := c.request(ctx, apiUrl+"/rest/Power/query", params) // 定义 var response RestPowerQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.recharge.cancel.go b/service/wikeyun/rest.recharge.cancel.go index c9913a6c..5a5edf84 100644 --- a/service/wikeyun/rest.recharge.cancel.go +++ b/service/wikeyun/rest.recharge.cancel.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -24,13 +25,13 @@ func newRestRechargeCancelResult(result RestRechargeCancelResponse, body []byte, // RestRechargeCancel 话费订单取消 // https://open.wikeyun.cn/#/apiDocument/9/document/300 -func (c *Client) RestRechargeCancel(orderNumber string) *RestRechargeCancelResult { +func (c *Client) RestRechargeCancel(ctx context.Context, orderNumber string) *RestRechargeCancelResult { // 参数 param := gorequest.NewParams() param.Set("order_number", orderNumber) // 取消的单号,多个用英文逗号隔开 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Recharge/cancel", params) + request, err := c.request(ctx, apiUrl+"/rest/Recharge/cancel", params) // 定义 var response RestRechargeCancelResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.recharge.mobileInfo.go b/service/wikeyun/rest.recharge.mobileInfo.go index bb093d8d..d331f220 100644 --- a/service/wikeyun/rest.recharge.mobileInfo.go +++ b/service/wikeyun/rest.recharge.mobileInfo.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -44,13 +45,13 @@ func newRestRechargeMobileInfoResult(result RestRechargeMobileInfoResponse, body // RestRechargeMobileInfo 查询手机归属地信息以及是否携号转网 // https://open.wikeyun.cn/#/apiDocument/9/document/374 -func (c *Client) RestRechargeMobileInfo(orderNumber string) *RestRechargeMobileInfoResult { +func (c *Client) RestRechargeMobileInfo(ctx context.Context, orderNumber string) *RestRechargeMobileInfoResult { // 参数 param := gorequest.NewParams() param.Set("order_number", orderNumber) // 平台单号 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Recharge/mobileInfo", params) + request, err := c.request(ctx, apiUrl+"/rest/Recharge/mobileInfo", params) // 定义 var response RestRechargeMobileInfoResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.recharge.push_order.go b/service/wikeyun/rest.recharge.push_order.go index 755fce9d..9a7d3f61 100644 --- a/service/wikeyun/rest.recharge.push_order.go +++ b/service/wikeyun/rest.recharge.push_order.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -26,12 +27,12 @@ func newRestRechargePushOrderResult(result RestRechargePushOrderResponse, body [ // RestRechargePushOrder 话费充值推送 // https://open.wikeyun.cn/#/apiDocument/9/document/298 -func (c *Client) RestRechargePushOrder(notMustParams ...gorequest.Params) *RestRechargePushOrderResult { +func (c *Client) RestRechargePushOrder(ctx context.Context, notMustParams ...gorequest.Params) *RestRechargePushOrderResult { // 参数 params := gorequest.NewParamsWith(notMustParams...) params.Set("store_id", c.config.StoreId) // 店铺ID // 请求 - request, err := c.request(apiUrl+"/rest/Recharge/pushOrder", params) + request, err := c.request(ctx, apiUrl+"/rest/Recharge/pushOrder", params) // 定义 var response RestRechargePushOrderResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.recharge.query.go b/service/wikeyun/rest.recharge.query.go index 69e44b88..2c55a458 100644 --- a/service/wikeyun/rest.recharge.query.go +++ b/service/wikeyun/rest.recharge.query.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -10,13 +11,14 @@ type RestRechargeQueryResponse struct { Msg string `json:"msg"` Time string `json:"time"` Data struct { - OrderNumber string `json:"order_number"` - OrderNo string `json:"order_no"` - Mobile string `json:"mobile"` - Amount int `json:"amount"` - CostPrice string `json:"cost_price"` + Id uint `json:"id"` Fanli string `json:"fanli"` + Amount int64 `json:"amount"` + Mobile string `json:"mobile"` Status int `json:"status"` + OrderNo string `json:"order_no"` + CostPrice string `json:"cost_price"` + OrderNumber string `json:"order_number"` OrgOrderNumber string `json:"org_order_number"` } `json:"data"` } @@ -34,13 +36,13 @@ func newRestRechargeQueryResult(result RestRechargeQueryResponse, body []byte, h // RestRechargeQuery 话费订单查询 // https://open.wikeyun.cn/#/apiDocument/9/document/299 -func (c *Client) RestRechargeQuery(orderNumber string) *RestRechargeQueryResult { +func (c *Client) RestRechargeQuery(ctx context.Context, orderNumber string) *RestRechargeQueryResult { // 参数 param := gorequest.NewParams() param.Set("order_number", orderNumber) // 平台订单号 params := gorequest.NewParamsWith(param) // 请求 - request, err := c.request(apiUrl+"/rest/Recharge/query", params) + request, err := c.request(ctx, apiUrl+"/rest/Recharge/query", params) // 定义 var response RestRechargeQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/service/wikeyun/rest.recharge.verify.go b/service/wikeyun/rest.recharge.verify.go new file mode 100644 index 00000000..ba2e8b1c --- /dev/null +++ b/service/wikeyun/rest.recharge.verify.go @@ -0,0 +1,41 @@ +package wikeyun + +import ( + "context" + "encoding/json" + "github.com/dtapps/go-library/utils/gorequest" +) + +type RestRechargeVerifyResponse struct { + Code string `json:"code"` // 0000代表正常,其他代表不可下单。 + Msg string `json:"msg"` + Time string `json:"time"` +} + +type RestRechargeVerifyResult struct { + Result RestRechargeVerifyResponse // 结果 + Body []byte // 内容 + Http gorequest.Response // 请求 + Err error // 错误 +} + +func newRestRechargeVerifyResult(result RestRechargeVerifyResponse, body []byte, http gorequest.Response, err error) *RestRechargeVerifyResult { + return &RestRechargeVerifyResult{Result: result, Body: body, Http: http, Err: err} +} + +// RestRechargeVerify 话费充值验证 +// https://open.wikeyun.cn/#/apiDocument/9/document/405 +func (c *Client) RestRechargeVerify(ctx context.Context, mobile string, amount int64, rechargeType int) *RestRechargeVerifyResult { + // 参数 + param := gorequest.NewParams() + param.Set("mobile", mobile) // 需要充值的手机号 + param.Set("amount", amount) // 需要充值的金额 + param.Set("recharge_type", rechargeType) // 充值类型 + params := gorequest.NewParamsWith(param) + // 请求 + request, err := c.request(ctx, apiUrl+"/rest/Recharge/verify", params) + // 定义 + var response RestRechargeVerifyResponse + err = json.Unmarshal(request.ResponseBody, &response) + return newRestRechargeVerifyResult(response, request.ResponseBody, request, err) +} diff --git a/service/wikeyun/rest.user.query.go b/service/wikeyun/rest.user.query.go index 089ac428..b6cd9065 100644 --- a/service/wikeyun/rest.user.query.go +++ b/service/wikeyun/rest.user.query.go @@ -1,6 +1,7 @@ package wikeyun import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" ) @@ -29,9 +30,9 @@ func newRestUserQueryResult(result RestUserQueryResponse, body []byte, http gore // RestUserQuery 用户信息 // https://open.wikeyun.cn/#/apiDocument/10/document/336 -func (c *Client) RestUserQuery() *RestUserQueryResult { +func (c *Client) RestUserQuery(ctx context.Context) *RestUserQueryResult { // 请求 - request, err := c.request(apiUrl+"/rest/User/query", map[string]interface{}{}) + request, err := c.request(ctx, apiUrl+"/rest/User/query", map[string]interface{}{}) // 定义 var response RestUserQueryResponse err = json.Unmarshal(request.ResponseBody, &response) diff --git a/utils/dorm/beego.go b/utils/dorm/beego.go deleted file mode 100644 index 443fdfe1..00000000 --- a/utils/dorm/beego.go +++ /dev/null @@ -1,16 +0,0 @@ -package dorm - -import ( - "github.com/beego/beego/v2/client/orm" -) - -type ConfigBeegoClient struct { - Dns string // 地址 -} - -// BeegoClient -// https://beego.vip/ -type BeegoClient struct { - Db *orm.Ormer // 驱动 - config *ConfigBeegoClient // 配置 -} diff --git a/utils/dorm/beego_mysql.go b/utils/dorm/beego_mysql.go deleted file mode 100644 index 31fb4341..00000000 --- a/utils/dorm/beego_mysql.go +++ /dev/null @@ -1,29 +0,0 @@ -package dorm - -import ( - "database/sql" - "errors" - "fmt" - "github.com/beego/beego/v2/client/orm" - _ "github.com/go-sql-driver/mysql" -) - -func NewBeegoMysqlClient(config *ConfigBeegoClient) (*BeegoClient, error) { - - var err error - c := &BeegoClient{config: config} - - err = orm.RegisterDriver("mysql", orm.DRMySQL) - if err != nil { - return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err)) - } - - var db *sql.DB - o, err := orm.NewOrmWithDB("mysql", "default", db) - if err != nil { - return nil, err - } - c.Db = &o - - return c, nil -} diff --git a/utils/dorm/beego_oracle.go b/utils/dorm/beego_oracle.go deleted file mode 100644 index 43cb0ca8..00000000 --- a/utils/dorm/beego_oracle.go +++ /dev/null @@ -1,29 +0,0 @@ -package dorm - -import ( - "database/sql" - "errors" - "fmt" - "github.com/beego/beego/v2/client/orm" - _ "github.com/lib/pq" -) - -func NewBeegoOracleClient(config *ConfigBeegoClient) (*BeegoClient, error) { - - var err error - c := &BeegoClient{config: config} - - err = orm.RegisterDriver("oracle", orm.DROracle) - if err != nil { - return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err)) - } - - var db *sql.DB - o, err := orm.NewOrmWithDB("oracle", "default", db) - if err != nil { - return nil, err - } - c.Db = &o - - return c, nil -} diff --git a/utils/dorm/beego_pgsql.go b/utils/dorm/beego_pgsql.go deleted file mode 100644 index 91a1d675..00000000 --- a/utils/dorm/beego_pgsql.go +++ /dev/null @@ -1,29 +0,0 @@ -package dorm - -import ( - "database/sql" - "errors" - "fmt" - "github.com/beego/beego/v2/client/orm" - _ "github.com/lib/pq" -) - -func NewBeegoPgsqlClient(config *ConfigBeegoClient) (*BeegoClient, error) { - - var err error - c := &BeegoClient{config: config} - - err = orm.RegisterDriver("pgsql", orm.DRPostgres) - if err != nil { - return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err)) - } - - var db *sql.DB - o, err := orm.NewOrmWithDB("pgsql", "default", db) - if err != nil { - return nil, err - } - c.Db = &o - - return c, nil -} diff --git a/utils/dorm/beego_tidb.go b/utils/dorm/beego_tidb.go deleted file mode 100644 index 671a57c3..00000000 --- a/utils/dorm/beego_tidb.go +++ /dev/null @@ -1,29 +0,0 @@ -package dorm - -import ( - "database/sql" - "errors" - "fmt" - "github.com/beego/beego/v2/client/orm" - _ "github.com/lib/pq" -) - -func NewBeegoTidbClient(config *ConfigBeegoClient) (*BeegoClient, error) { - - var err error - c := &BeegoClient{config: config} - - err = orm.RegisterDriver("TiDB", orm.DRTiDB) - if err != nil { - return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err)) - } - - var db *sql.DB - o, err := orm.NewOrmWithDB("TiDB", "default", db) - if err != nil { - return nil, err - } - c.Db = &o - - return c, nil -} diff --git a/utils/dorm/bun_get.go b/utils/dorm/bun_get.go new file mode 100644 index 00000000..b877d889 --- /dev/null +++ b/utils/dorm/bun_get.go @@ -0,0 +1,10 @@ +package dorm + +import ( + "github.com/uptrace/bun" +) + +// GetDb 获取驱动 +func (c *BunClient) GetDb() *bun.DB { + return c.Db +} diff --git a/utils/dorm/bun_mssql.go b/utils/dorm/bun_mssql.go deleted file mode 100644 index c21b13f9..00000000 --- a/utils/dorm/bun_mssql.go +++ /dev/null @@ -1,25 +0,0 @@ -package dorm - -import ( - "database/sql" - "errors" - "fmt" - _ "github.com/denisenkom/go-mssqldb" - "github.com/uptrace/bun" - "github.com/uptrace/bun/dialect/mssqldialect" -) - -func NewBunMssqlClient(config *ConfigBunClient) (*BunClient, error) { - - var err error - c := &BunClient{config: config} - - sqlDb, err := sql.Open("sqlserver", c.config.Dns) - if err != nil { - return nil, errors.New(fmt.Sprintf("加载驱动失败:%v", err)) - } - - c.Db = bun.NewDB(sqlDb, mssqldialect.New()) - - return c, nil -} diff --git a/utils/dorm/gorm.go b/utils/dorm/gorm.go index 720de0a2..afa89828 100644 --- a/utils/dorm/gorm.go +++ b/utils/dorm/gorm.go @@ -10,9 +10,20 @@ import ( ) type ConfigGormClient struct { - Dns string // 地址 - Log bool // 日志 - LogUrl string // 日志路径 + Dns string // 地址 + Log struct { + Status bool // 状态 + Path string // 路径 + Slow int64 // 慢SQL阈值 + Level string // 级别 + NotFoundError bool // 忽略ErrRecordNotFound(记录未找到)错误 + Colorful bool // 禁用彩色打印 + } // 日志 + Conn struct { + SetMaxIdle int // 设置空闲连接池中连接的最大数量 + SetMaxOpen int // 设置打开数据库连接的最大数量 + SetConnMaxLifetime int64 // 设置了连接可复用的最大时间 + } // 连接 } // GormClient @@ -22,10 +33,6 @@ type GormClient struct { config *ConfigGormClient // 配置 } -func (c *GormClient) GetDb() *gorm.DB { - return c.Db -} - type writer struct{} // 日志路径 diff --git a/utils/dorm/gorm_get.go b/utils/dorm/gorm_get.go new file mode 100644 index 00000000..613d3bd6 --- /dev/null +++ b/utils/dorm/gorm_get.go @@ -0,0 +1,8 @@ +package dorm + +import "gorm.io/gorm" + +// GetDb 获取驱动 +func (c *GormClient) GetDb() *gorm.DB { + return c.Db +} diff --git a/utils/dorm/gorm_mysql.go b/utils/dorm/gorm_mysql.go index 826bf50c..182db01a 100644 --- a/utils/dorm/gorm_mysql.go +++ b/utils/dorm/gorm_mysql.go @@ -16,19 +16,35 @@ func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) { c := &GormClient{config: config} // 判断路径 - if c.config.LogUrl == "" { + if c.config.Log.Path == "" { logsUrl = "/logs/mysql" + } else { + logsUrl = c.config.Log.Path } - if c.config.Log == true { + if c.config.Log.Status == true { + var slowThreshold time.Duration + var logLevel logger.LogLevel + if c.config.Log.Slow == 0 { + slowThreshold = 100 * time.Millisecond + } else { + slowThreshold = time.Duration(c.config.Log.Slow) + } + if c.config.Log.Level == "Error" { + logLevel = logger.Error + } else if c.config.Log.Level == "Warn" { + logLevel = logger.Warn + } else { + logLevel = logger.Info + } c.Db, err = gorm.Open(mysql.Open(c.config.Dns), &gorm.Config{ Logger: logger.New( writer{}, logger.Config{ - SlowThreshold: time.Second, // 慢 SQL 阈值 - LogLevel: logger.Info, // 日志级别 - IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound(记录未找到)错误 - Colorful: false, // 禁用彩色打印 + SlowThreshold: slowThreshold, // 慢SQL阈值 + LogLevel: logLevel, // 日志级别 + IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound(记录未找到)错误 + Colorful: c.config.Log.Colorful, // 禁用彩色打印 }, ), NowFunc: func() time.Time { @@ -48,9 +64,26 @@ func NewGormMysqlClient(config *ConfigGormClient) (*GormClient, error) { return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err)) } - sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量 - sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。 - sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。 + // 设置空闲连接池中连接的最大数量 + if c.config.Conn.SetMaxIdle == 0 { + sqlDB.SetMaxIdleConns(10) + } else { + sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle) + } + + // 设置打开数据库连接的最大数量 + if c.config.Conn.SetMaxOpen == 0 { + sqlDB.SetMaxOpenConns(100) + } else { + sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen) + } + + // 设置了连接可复用的最大时间 + if c.config.Conn.SetConnMaxLifetime == 0 { + sqlDB.SetConnMaxLifetime(time.Second * 600) + } else { + sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime)) + } return c, nil } diff --git a/utils/dorm/gorm_postgresql.go b/utils/dorm/gorm_postgresql.go index e52f28ee..2caf842d 100644 --- a/utils/dorm/gorm_postgresql.go +++ b/utils/dorm/gorm_postgresql.go @@ -12,25 +12,40 @@ import ( func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) { + var err error c := &GormClient{} c.config = config // 判断路径 - if c.config.LogUrl == "" { + if c.config.Log.Path == "" { logsUrl = "/logs/postgresql" + } else { + logsUrl = c.config.Log.Path } - var err error - - if c.config.Log == true { + if c.config.Log.Status == true { + var slowThreshold time.Duration + var logLevel logger.LogLevel + if c.config.Log.Slow == 0 { + slowThreshold = 100 * time.Millisecond + } else { + slowThreshold = time.Duration(c.config.Log.Slow) + } + if c.config.Log.Level == "Error" { + logLevel = logger.Error + } else if c.config.Log.Level == "Warn" { + logLevel = logger.Warn + } else { + logLevel = logger.Info + } c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{ Logger: logger.New( writer{}, logger.Config{ - SlowThreshold: time.Second, // 慢 SQL 阈值 - LogLevel: logger.Info, // 日志级别 - IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound(记录未找到)错误 - Colorful: false, // 禁用彩色打印 + SlowThreshold: slowThreshold, // 慢SQL阈值 + LogLevel: logLevel, // 日志级别 + IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound(记录未找到)错误 + Colorful: c.config.Log.Colorful, // 禁用彩色打印 }, ), NowFunc: func() time.Time { @@ -50,34 +65,66 @@ func NewGormPostgresClient(config *ConfigGormClient) (*GormClient, error) { return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err)) } - sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量 - sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。 - sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。 + // 设置空闲连接池中连接的最大数量 + if c.config.Conn.SetMaxIdle == 0 { + sqlDB.SetMaxIdleConns(10) + } else { + sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle) + } + + // 设置打开数据库连接的最大数量 + if c.config.Conn.SetMaxOpen == 0 { + sqlDB.SetMaxOpenConns(100) + } else { + sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen) + } + + // 设置了连接可复用的最大时间 + if c.config.Conn.SetConnMaxLifetime == 0 { + sqlDB.SetConnMaxLifetime(time.Second * 600) + } else { + sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime)) + } return c, nil } func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) { + var err error c := &GormClient{} c.config = config // 判断路径 - if c.config.LogUrl == "" { + if c.config.Log.Path == "" { logsUrl = "/logs/postgresql" + } else { + logsUrl = c.config.Log.Path } - var err error - - if c.config.Log == true { + if c.config.Log.Status == true { + var slowThreshold time.Duration + var logLevel logger.LogLevel + if c.config.Log.Slow == 0 { + slowThreshold = 100 * time.Millisecond + } else { + slowThreshold = time.Duration(c.config.Log.Slow) + } + if c.config.Log.Level == "Error" { + logLevel = logger.Error + } else if c.config.Log.Level == "Warn" { + logLevel = logger.Warn + } else { + logLevel = logger.Info + } c.Db, err = gorm.Open(postgres.Open(c.config.Dns), &gorm.Config{ Logger: logger.New( writer{}, logger.Config{ - SlowThreshold: time.Second, // 慢 SQL 阈值 - LogLevel: logger.Info, // 日志级别 - IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound(记录未找到)错误 - Colorful: false, // 禁用彩色打印 + SlowThreshold: slowThreshold, // 慢SQL阈值 + LogLevel: logLevel, // 日志级别 + IgnoreRecordNotFoundError: c.config.Log.NotFoundError, // 忽略ErrRecordNotFound(记录未找到)错误 + Colorful: c.config.Log.Colorful, // 禁用彩色打印 }, ), NowFunc: func() time.Time { @@ -97,9 +144,26 @@ func NewGormPostgresqlClient(config *ConfigGormClient) (*GormClient, error) { return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err)) } - sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量 - sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。 - sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。 + // 设置空闲连接池中连接的最大数量 + if c.config.Conn.SetMaxIdle == 0 { + sqlDB.SetMaxIdleConns(10) + } else { + sqlDB.SetMaxIdleConns(c.config.Conn.SetMaxIdle) + } + + // 设置打开数据库连接的最大数量 + if c.config.Conn.SetMaxOpen == 0 { + sqlDB.SetMaxOpenConns(100) + } else { + sqlDB.SetMaxOpenConns(c.config.Conn.SetMaxOpen) + } + + // 设置了连接可复用的最大时间 + if c.config.Conn.SetConnMaxLifetime == 0 { + sqlDB.SetConnMaxLifetime(time.Second * 600) + } else { + sqlDB.SetConnMaxLifetime(time.Duration(c.config.Conn.SetConnMaxLifetime)) + } return c, nil } diff --git a/utils/dorm/gorm_sqlserver.go b/utils/dorm/gorm_sqlserver.go deleted file mode 100644 index 89bd8bf7..00000000 --- a/utils/dorm/gorm_sqlserver.go +++ /dev/null @@ -1,56 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "github.com/dtapps/go-library/utils/gotime" - "gorm.io/driver/sqlserver" - "gorm.io/gorm" - "gorm.io/gorm/logger" - "time" -) - -func NewGormSqlServerClient(config *ConfigGormClient) (*GormClient, error) { - - var err error - c := &GormClient{config: config} - - // 判断路径 - if c.config.LogUrl == "" { - logsUrl = "/logs/sqlserver" - } - - if c.config.Log == true { - c.Db, err = gorm.Open(sqlserver.Open(c.config.Dns), &gorm.Config{ - Logger: logger.New( - writer{}, - logger.Config{ - SlowThreshold: time.Second, // 慢 SQL 阈值 - LogLevel: logger.Info, // 日志级别 - IgnoreRecordNotFoundError: true, // 忽略ErrRecordNotFound(记录未找到)错误 - Colorful: false, // 禁用彩色打印 - }, - ), - NowFunc: func() time.Time { - return gotime.Current().Now().Local() - }, - }) - } else { - c.Db, err = gorm.Open(sqlserver.Open(c.config.Dns), &gorm.Config{}) - } - - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - sqlDB, err := c.Db.DB() - if err != nil { - return nil, errors.New(fmt.Sprintf("检查连接失败:%v", err)) - } - - sqlDB.SetMaxIdleConns(10) // 设置空闲连接池中连接的最大数量 - sqlDB.SetMaxOpenConns(100) // 设置打开数据库连接的最大数量。 - sqlDB.SetConnMaxLifetime(time.Second * 600) // 设置了连接可复用的最大时间。 - - return c, nil -} diff --git a/utils/dorm/redis.go b/utils/dorm/redis.go index d9fde1ff..96cc95f5 100644 --- a/utils/dorm/redis.go +++ b/utils/dorm/redis.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "github.com/go-redis/redis/v8" + "github.com/go-redis/redis/v9" "time" ) @@ -47,7 +47,3 @@ func NewRedisClient(config *ConfigRedisClient) (*RedisClient, error) { return c, nil } - -func (c *RedisClient) GetDb() *redis.Client { - return c.Db -} diff --git a/utils/dorm/redis_6.go b/utils/dorm/redis_6.go deleted file mode 100644 index e72b0d0b..00000000 --- a/utils/dorm/redis_6.go +++ /dev/null @@ -1,47 +0,0 @@ -package dorm - -import ( - "context" - "errors" - "fmt" - "github.com/go-redis/redis/v8" - "time" -) - -// RedisClient6 -// https://redis.uptrace.dev/ -type RedisClient6 struct { - Db *redis.Client // 驱动 - config *ConfigRedisClient // 配置 -} - -// NewRedisClient6 Redis 6 -func NewRedisClient6(config *ConfigRedisClient) (*RedisClient6, error) { - - c := &RedisClient6{} - c.config = config - if c.config.PoolSize == 0 { - c.config.PoolSize = 100 - } - - c.Db = redis.NewClient(&redis.Options{ - Addr: c.config.Addr, // 地址 - Password: c.config.Password, // 密码 - DB: c.config.DB, // 数据库 - PoolSize: c.config.PoolSize, // 连接池大小 - }) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - _, err := c.Db.Ping(ctx).Result() - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - return c, nil -} - -func (c *RedisClient6) GetDb() *redis.Client { - return c.Db -} diff --git a/utils/dorm/redis_7.go b/utils/dorm/redis_7.go deleted file mode 100644 index f4893f66..00000000 --- a/utils/dorm/redis_7.go +++ /dev/null @@ -1,47 +0,0 @@ -package dorm - -import ( - "context" - "errors" - "fmt" - "github.com/go-redis/redis/v9" - "time" -) - -// RedisClient7 -// https://redis.uptrace.dev/ -type RedisClient7 struct { - Db *redis.Client // 驱动 - config *ConfigRedisClient // 配置 -} - -// NewRedisClient7 Redis 7 -func NewRedisClient7(config *ConfigRedisClient) (*RedisClient7, error) { - - c := &RedisClient7{} - c.config = config - if c.config.PoolSize == 0 { - c.config.PoolSize = 100 - } - - c.Db = redis.NewClient(&redis.Options{ - Addr: c.config.Addr, // 地址 - Password: c.config.Password, // 密码 - DB: c.config.DB, // 数据库 - PoolSize: c.config.PoolSize, // 连接池大小 - }) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - _, err := c.Db.Ping(ctx).Result() - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - return c, nil -} - -func (c *RedisClient7) GetDb() *redis.Client { - return c.Db -} diff --git a/utils/dorm/redis_cache.go b/utils/dorm/redis_cache.go new file mode 100644 index 00000000..3be9993c --- /dev/null +++ b/utils/dorm/redis_cache.go @@ -0,0 +1,96 @@ +package dorm + +import ( + "context" + "encoding/json" + "time" +) + +// GttStringFunc String缓存结构 +type GttStringFunc func() string + +// GttInterfaceFunc Interface缓存结构 +type GttInterfaceFunc func() interface{} + +// RedisCacheConfig 配置 +type RedisCacheConfig struct { + Expiration time.Duration // 过期时间 +} + +// RedisClientCache https://github.com/go-redis/redis +type RedisClientCache struct { + defaultExpiration time.Duration // 过期时间 + operation *RedisClient // 操作 + GetterString GttStringFunc // 不存在的操作 + GetterInterface GttInterfaceFunc // 不存在的操作 +} + +// NewCache 实例化 +func (r *RedisClient) NewCache(config *RedisCacheConfig) *RedisClientCache { + return &RedisClientCache{ + defaultExpiration: config.Expiration, + operation: r, + } +} + +// NewCacheDefaultExpiration 实例化 +func (r *RedisClient) NewCacheDefaultExpiration() *RedisClientCache { + return &RedisClientCache{ + defaultExpiration: time.Minute * 30, + operation: r, + } +} + +// GetString 缓存操作 +func (rc *RedisClientCache) GetString(ctx context.Context, key string) (ret string) { + + f := func() string { + return rc.GetterString() + } + + // 如果不存在,则调用GetterString + ret, err := rc.operation.Get(ctx, key).Result() + if err != nil { + rc.operation.Set(ctx, key, f(), rc.defaultExpiration) + ret, _ = rc.operation.Get(ctx, key).Result() + } + + return +} + +// GetInterface 缓存操作 +func (rc *RedisClientCache) GetInterface(ctx context.Context, key string, result interface{}) { + + f := func() string { + marshal, _ := json.Marshal(rc.GetterInterface()) + return string(marshal) + } + + // 如果不存在,则调用GetterInterface + ret, err := rc.operation.Get(ctx, key).Result() + + if err != nil { + rc.operation.Set(ctx, key, f(), rc.defaultExpiration) + ret, _ = rc.operation.Get(ctx, key).Result() + } + + err = json.Unmarshal([]byte(ret), result) + + return +} + +// GetInterfaceKey 获取key值 +func (rc *RedisClientCache) GetInterfaceKey(ctx context.Context, key string, result interface{}) error { + ret, err := rc.operation.Get(ctx, key).Result() + if err != nil { + return err + } + err = json.Unmarshal([]byte(ret), result) + return nil +} + +// SetInterfaceKey 设置key值 +func (rc *RedisClientCache) SetInterfaceKey(ctx context.Context, key string, value interface{}) (string, error) { + marshal, _ := json.Marshal(value) + return rc.operation.Set(ctx, key, marshal, rc.defaultExpiration).Result() +} diff --git a/utils/dorm/redis_curd.go b/utils/dorm/redis_curd.go new file mode 100644 index 00000000..93ac65e3 --- /dev/null +++ b/utils/dorm/redis_curd.go @@ -0,0 +1,76 @@ +package dorm + +import ( + "context" + "github.com/go-redis/redis/v9" + "time" +) + +// Set 设置一个key的值 +func (r *RedisClient) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.StatusCmd { + return r.Db.Set(ctx, key, value, expiration) +} + +// Get 查询key的值 +func (r *RedisClient) Get(ctx context.Context, key string) *redis.StringCmd { + return r.Db.Get(ctx, key) +} + +// GetSet 设置一个key的值,并返回这个key的旧值 +func (r *RedisClient) GetSet(ctx context.Context, key string, value interface{}) *redis.StringCmd { + return r.Db.GetSet(ctx, key, value) +} + +// SetNX 如果key不存在,则设置这个key的值 +func (r *RedisClient) SetNX(ctx context.Context, key string, value interface{}, expiration time.Duration) *redis.BoolCmd { + return r.Db.SetNX(ctx, key, value, expiration) +} + +// MGet 批量查询key的值 +func (r *RedisClient) MGet(ctx context.Context, keys ...string) *redis.SliceCmd { + return r.Db.MGet(ctx, keys...) +} + +// MSet 批量设置key的值 +// MSet(map[string]interface{}{"key1": "value1", "key2": "value2"}) +func (r *RedisClient) MSet(ctx context.Context, values map[string]interface{}) *redis.StatusCmd { + return r.Db.MSet(ctx, values) +} + +// Incr 针对一个key的数值进行递增操作 +func (r *RedisClient) Incr(ctx context.Context, key string) *redis.IntCmd { + return r.Db.Incr(ctx, key) +} + +// IncrBy 针对一个key的数值进行递增操作,指定每次递增多少 +func (r *RedisClient) IncrBy(ctx context.Context, key string, value int64) *redis.IntCmd { + return r.Db.IncrBy(ctx, key, value) +} + +// Decr 针对一个key的数值进行递减操作 +func (r *RedisClient) Decr(ctx context.Context, key string) *redis.IntCmd { + return r.Db.Decr(ctx, key) +} + +// DecrBy 针对一个key的数值进行递减操作,指定每次递减多少 +func (r *RedisClient) DecrBy(ctx context.Context, key string, value int64) *redis.IntCmd { + return r.Db.DecrBy(ctx, key, value) +} + +// Del 删除key操作,支持批量删除 +func (r *RedisClient) Del(ctx context.Context, keys ...string) *redis.IntCmd { + return r.Db.Del(ctx, keys...) +} + +// Keys 按前缀获取所有 key +func (r *RedisClient) Keys(ctx context.Context, prefix string) *redis.SliceCmd { + values, _ := r.Db.Keys(ctx, prefix).Result() + if len(values) <= 0 { + return &redis.SliceCmd{} + } + keys := make([]string, 0, len(values)) + for _, value := range values { + keys = append(keys, value) + } + return r.MGet(ctx, keys...) +} diff --git a/utils/dorm/redis_curd_channel.go b/utils/dorm/redis_curd_channel.go new file mode 100644 index 00000000..bb57a0d2 --- /dev/null +++ b/utils/dorm/redis_curd_channel.go @@ -0,0 +1,31 @@ +package dorm + +import ( + "context" + "github.com/go-redis/redis/v9" +) + +// Subscribe 订阅channel +func (r *RedisClient) Subscribe(ctx context.Context, channels ...string) *redis.PubSub { + return r.Db.Subscribe(ctx, channels...) +} + +// PSubscribe 订阅channel支持通配符匹配 +func (r *RedisClient) PSubscribe(ctx context.Context, channels ...string) *redis.PubSub { + return r.Db.PSubscribe(ctx, channels...) +} + +// Publish 将信息发送到指定的channel +func (r *RedisClient) Publish(ctx context.Context, channel string, message interface{}) *redis.IntCmd { + return r.Db.Publish(ctx, channel, message) +} + +// PubSubChannels 查询活跃的channel +func (r *RedisClient) PubSubChannels(ctx context.Context, pattern string) *redis.StringSliceCmd { + return r.Db.PubSubChannels(ctx, pattern) +} + +// PubSubNumSub 查询指定的channel有多少个订阅者 +func (r *RedisClient) PubSubNumSub(ctx context.Context, channels ...string) *redis.StringIntMapCmd { + return r.Db.PubSubNumSub(ctx, channels...) +} diff --git a/utils/dorm/redis_get.go b/utils/dorm/redis_get.go new file mode 100644 index 00000000..af04c438 --- /dev/null +++ b/utils/dorm/redis_get.go @@ -0,0 +1,8 @@ +package dorm + +import "github.com/go-redis/redis/v9" + +// GetDb 获取驱动 +func (r *RedisClient) GetDb() *redis.Client { + return r.Db +} diff --git a/utils/dorm/redis_hash_operation.go b/utils/dorm/redis_hash_operation.go index ca8c2a21..6e29e1d7 100644 --- a/utils/dorm/redis_hash_operation.go +++ b/utils/dorm/redis_hash_operation.go @@ -2,7 +2,7 @@ package dorm import ( "context" - "github.com/go-redis/redis/v8" + "github.com/go-redis/redis/v9" ) type HashOperation struct { diff --git a/utils/dorm/redis_list_operation.go b/utils/dorm/redis_list_operation.go index 7cf7921a..9831b738 100644 --- a/utils/dorm/redis_list_operation.go +++ b/utils/dorm/redis_list_operation.go @@ -2,7 +2,7 @@ package dorm import ( "context" - "github.com/go-redis/redis/v8" + "github.com/go-redis/redis/v9" ) type ListOperation struct { @@ -11,8 +11,8 @@ type ListOperation struct { } // NewListOperation 列表(list)类型数据操作 https://www.tizi365.com/archives/299.html -func (c *RedisClient) NewListOperation() *ListOperation { - return &ListOperation{db: c.Db, ctx: context.Background()} +func (r *RedisClient) NewListOperation() *ListOperation { + return &ListOperation{db: r.Db, ctx: context.Background()} } // LPush 从列表左边插入数据 diff --git a/utils/dorm/redis_simple_cache.go b/utils/dorm/redis_simple_cache.go index 667d26f5..e760b1bf 100644 --- a/utils/dorm/redis_simple_cache.go +++ b/utils/dorm/redis_simple_cache.go @@ -24,7 +24,7 @@ type SimpleCache struct { } // NewSimpleCache 构造函数 -func (c *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache { +func (r *RedisClient) NewSimpleCache(operation *StringOperation, expire time.Duration, serializer string) *SimpleCache { return &SimpleCache{ Operation: operation, // 操作类 Expire: expire, // 过去时间 diff --git a/utils/dorm/redis_simple_interface_cache.go b/utils/dorm/redis_simple_interface_cache.go index 3a4fba15..795b4923 100644 --- a/utils/dorm/redis_simple_interface_cache.go +++ b/utils/dorm/redis_simple_interface_cache.go @@ -15,7 +15,7 @@ type SimpleInterfaceCache struct { } // NewSimpleInterfaceCache 构造函数 -func (c *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire time.Duration) *SimpleInterfaceCache { +func (r *RedisClient) NewSimpleInterfaceCache(operation *SimpleOperation, expire time.Duration) *SimpleInterfaceCache { return &SimpleInterfaceCache{ Operation: operation, // 操作类 Expire: expire, // 过期时间 diff --git a/utils/dorm/redis_simple_json_cache.go b/utils/dorm/redis_simple_json_cache.go index ddbdf71d..d51f8a60 100644 --- a/utils/dorm/redis_simple_json_cache.go +++ b/utils/dorm/redis_simple_json_cache.go @@ -15,7 +15,7 @@ type SimpleJsonCache struct { } // NewSimpleJsonCache 构造函数 -func (c *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time.Duration) *SimpleJsonCache { +func (r *RedisClient) NewSimpleJsonCache(operation *StringOperation, expire time.Duration) *SimpleJsonCache { return &SimpleJsonCache{ Operation: operation, // 操作类 Expire: expire, // 过期时间 diff --git a/utils/dorm/redis_simple_operation.go b/utils/dorm/redis_simple_operation.go index 3496d845..661ba46f 100644 --- a/utils/dorm/redis_simple_operation.go +++ b/utils/dorm/redis_simple_operation.go @@ -2,7 +2,7 @@ package dorm import ( "context" - "github.com/go-redis/redis/v8" + "github.com/go-redis/redis/v9" "time" ) @@ -11,9 +11,9 @@ type SimpleOperation struct { ctx context.Context } -func (c *RedisClient) NewSimpleOperation() *SimpleOperation { +func (r *RedisClient) NewSimpleOperation() *SimpleOperation { return &SimpleOperation{ - db: c.Db, + db: r.Db, ctx: context.Background(), } } diff --git a/utils/dorm/redis_simple_sring_cache.go b/utils/dorm/redis_simple_sring_cache.go index 2889d032..1216ab8e 100644 --- a/utils/dorm/redis_simple_sring_cache.go +++ b/utils/dorm/redis_simple_sring_cache.go @@ -14,7 +14,7 @@ type SimpleStringCache struct { } // NewSimpleStringCache 构造函数 -func (c *RedisClient) NewSimpleStringCache(operation *StringOperation, expire time.Duration) *SimpleStringCache { +func (r *RedisClient) NewSimpleStringCache(operation *StringOperation, expire time.Duration) *SimpleStringCache { return &SimpleStringCache{ Operation: operation, // 操作类 Expire: expire, // 过期时间 diff --git a/utils/dorm/redis_string_operation.go b/utils/dorm/redis_string_operation.go index 439f5e59..c2c7ed3c 100644 --- a/utils/dorm/redis_string_operation.go +++ b/utils/dorm/redis_string_operation.go @@ -2,7 +2,7 @@ package dorm import ( "context" - "github.com/go-redis/redis/v8" + "github.com/go-redis/redis/v9" "time" ) @@ -11,9 +11,9 @@ type StringOperation struct { ctx context.Context } -func (c *RedisClient) NewStringOperation() *StringOperation { +func (r *RedisClient) NewStringOperation() *StringOperation { return &StringOperation{ - db: c.Db, + db: r.Db, ctx: context.Background(), } } diff --git a/utils/dorm/upper_cockroachdb.go b/utils/dorm/upper_cockroachdb.go deleted file mode 100644 index 523e9968..00000000 --- a/utils/dorm/upper_cockroachdb.go +++ /dev/null @@ -1,23 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "github.com/upper/db/v4/adapter/cockroachdb" -) - -func NewUpperCockroachdbClient(settings cockroachdb.ConnectionURL) (*UpperClient, error) { - - var err error - c := &UpperClient{} - - sess, err := cockroachdb.Open(settings) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - defer sess.Close() - - c.Db = &sess - - return c, nil -} diff --git a/utils/dorm/upper_get.go b/utils/dorm/upper_get.go new file mode 100644 index 00000000..2213f1f7 --- /dev/null +++ b/utils/dorm/upper_get.go @@ -0,0 +1,10 @@ +package dorm + +import ( + "github.com/upper/db/v4" +) + +// GetDb 获取驱动 +func (c *UpperClient) GetDb() *db.Session { + return c.Db +} diff --git a/utils/dorm/upper_mongodb.go b/utils/dorm/upper_mongodb.go deleted file mode 100644 index 2b0256fb..00000000 --- a/utils/dorm/upper_mongodb.go +++ /dev/null @@ -1,23 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "github.com/upper/db/v4/adapter/mongo" -) - -func NewUpperMongodbClient(settings mongo.ConnectionURL) (*UpperClient, error) { - - var err error - c := &UpperClient{} - - sess, err := mongo.Open(settings) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - defer sess.Close() - - c.Db = &sess - - return c, nil -} diff --git a/utils/dorm/upper_mssql.go b/utils/dorm/upper_mssql.go deleted file mode 100644 index d22edfc2..00000000 --- a/utils/dorm/upper_mssql.go +++ /dev/null @@ -1,23 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "github.com/upper/db/v4/adapter/mssql" -) - -func NewUpperMssqlClient(settings mssql.ConnectionURL) (*UpperClient, error) { - - var err error - c := &UpperClient{} - - sess, err := mssql.Open(settings) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - defer sess.Close() - - c.Db = &sess - - return c, nil -} diff --git a/utils/dorm/upper_ql.go b/utils/dorm/upper_ql.go deleted file mode 100644 index 4652c8f9..00000000 --- a/utils/dorm/upper_ql.go +++ /dev/null @@ -1,23 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "github.com/upper/db/v4/adapter/ql" -) - -func NewUpperQlClient(settings ql.ConnectionURL) (*UpperClient, error) { - - var err error - c := &UpperClient{} - - sess, err := ql.Open(settings) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - defer sess.Close() - - c.Db = &sess - - return c, nil -} diff --git a/utils/dorm/xorm_get.go b/utils/dorm/xorm_get.go new file mode 100644 index 00000000..394ccae7 --- /dev/null +++ b/utils/dorm/xorm_get.go @@ -0,0 +1,10 @@ +package dorm + +import ( + "xorm.io/xorm" +) + +// GetDb 获取驱动 +func (c *XormClient) GetDb() *xorm.Engine { + return c.Db +} diff --git a/utils/dorm/zorm.go b/utils/dorm/zorm.go deleted file mode 100644 index 076368c0..00000000 --- a/utils/dorm/zorm.go +++ /dev/null @@ -1,17 +0,0 @@ -package dorm - -import ( - "gitee.com/chunanyong/zorm" -) - -type ConfigZormClient struct { - Dns string // 地址 -} - -// ZormClient -// https://zorm.cn/ -// https://www.yuque.com/u27016943/nrgi00 -type ZormClient struct { - Db *zorm.DBDao // 驱动 - config *ConfigZormClient // 配置 -} diff --git a/utils/dorm/zorm_clickhouse.go b/utils/dorm/zorm_clickhouse.go deleted file mode 100644 index 769f4dad..00000000 --- a/utils/dorm/zorm_clickhouse.go +++ /dev/null @@ -1,31 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "gitee.com/chunanyong/zorm" - _ "github.com/mailru/go-clickhouse/v2" -) - -func NewZormClickhouseClient(config *ConfigZormClient) (*ZormClient, error) { - - var err error - c := &ZormClient{config: config} - - c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{ - DSN: c.config.Dns, - DriverName: "chhttp", // 数据库驱动名称 - DBType: "clickhouse", // 数据库类型 - PrintSQL: true, // 是否打印sql - MaxOpenConns: 0, // 数据库最大连接数,默认50 - MaxIdleConns: 0, // 数据库最大空闲连接数,默认50 - ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建. - // 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时) - DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil - }) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - return c, nil -} diff --git a/utils/dorm/zorm_dm.go b/utils/dorm/zorm_dm.go deleted file mode 100644 index b826e9fa..00000000 --- a/utils/dorm/zorm_dm.go +++ /dev/null @@ -1,31 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - _ "gitee.com/chunanyong/dm" - "gitee.com/chunanyong/zorm" -) - -func NewZormDmClient(config *ConfigZormClient) (*ZormClient, error) { - - var err error - c := &ZormClient{config: config} - - c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{ - DSN: c.config.Dns, - DriverName: "dm", // 数据库驱动名称 - DBType: "dm", // 数据库类型 - PrintSQL: true, // 是否打印sql - MaxOpenConns: 0, // 数据库最大连接数,默认50 - MaxIdleConns: 0, // 数据库最大空闲连接数,默认50 - ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建. - // 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时) - DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil - }) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - return c, nil -} diff --git a/utils/dorm/zorm_gbase.go b/utils/dorm/zorm_gbase.go deleted file mode 100644 index c3827735..00000000 --- a/utils/dorm/zorm_gbase.go +++ /dev/null @@ -1 +0,0 @@ -package dorm diff --git a/utils/dorm/zorm_kingbase.go b/utils/dorm/zorm_kingbase.go deleted file mode 100644 index c3827735..00000000 --- a/utils/dorm/zorm_kingbase.go +++ /dev/null @@ -1 +0,0 @@ -package dorm diff --git a/utils/dorm/zorm_mysql.go b/utils/dorm/zorm_mysql.go deleted file mode 100644 index 2ea6938d..00000000 --- a/utils/dorm/zorm_mysql.go +++ /dev/null @@ -1,31 +0,0 @@ -package dorm - -import ( - "errors" - "fmt" - "gitee.com/chunanyong/zorm" - _ "github.com/go-sql-driver/mysql" -) - -func NewZormMysqlClient(config *ConfigZormClient) (*ZormClient, error) { - - var err error - c := &ZormClient{config: config} - - c.Db, err = zorm.NewDBDao(&zorm.DataSourceConfig{ - DSN: c.config.Dns, - DriverName: "mysql", // 数据库驱动名称 - DBType: "mysql", // 数据库类型 - PrintSQL: true, // 是否打印sql - MaxOpenConns: 0, // 数据库最大连接数,默认50 - MaxIdleConns: 0, // 数据库最大空闲连接数,默认50 - ConnMaxLifetimeSecond: 0, // 连接存活秒时间. 默认600(10分钟)后连接被销毁重建. - // 避免数据库主动断开连接,造成死连接.MySQL默认wait_timeout 28800秒(8小时) - DefaultTxOptions: nil, // 事务隔离级别的默认配置,默认为nil - }) - if err != nil { - return nil, errors.New(fmt.Sprintf("连接失败:%v", err)) - } - - return c, nil -} diff --git a/utils/dorm/zorm_shentong.go b/utils/dorm/zorm_shentong.go deleted file mode 100644 index c3827735..00000000 --- a/utils/dorm/zorm_shentong.go +++ /dev/null @@ -1 +0,0 @@ -package dorm diff --git a/utils/gocache/big.go b/utils/gocache/big.go index 336e5815..36e3f484 100644 --- a/utils/gocache/big.go +++ b/utils/gocache/big.go @@ -14,16 +14,15 @@ type BigConfig struct { // Big https://github.com/allegro/bigcache type Big struct { - BigConfig - db *bigcache.BigCache // 驱动 + config *BigConfig + db *bigcache.BigCache // 驱动 } // NewBig 实例化 func NewBig(config *BigConfig) *Big { - app := &Big{} - app.DefaultExpiration = config.DefaultExpiration - app.db, _ = bigcache.NewBigCache(bigcache.DefaultConfig(app.DefaultExpiration)) - return app + c := &Big{config: config} + c.db, _ = bigcache.NewBigCache(bigcache.DefaultConfig(c.config.DefaultExpiration)) + return c } // Set 插入数据 将只显示给定结构的导出字段 序列化并存储 diff --git a/utils/gocache/etcd.go b/utils/gocache/etcd.go deleted file mode 100644 index 600c8dba..00000000 --- a/utils/gocache/etcd.go +++ /dev/null @@ -1,64 +0,0 @@ -package gocache - -import ( - "context" - "errors" - "go.etcd.io/etcd/client/v3" - "time" -) - -type EtcdConfig struct { - Endpoints []string // 接口 []string{"http://127.0.0.1:2379"} - DialTimeout time.Duration // time.Second * 5 -} - -type Etcd struct { - EtcdConfig // 配置 - Client *clientv3.Client // 驱动 - Kv clientv3.KV // kv API子集 - Lease clientv3.Lease // lease(租约)对象 - leaseId clientv3.LeaseID // 租约编号 -} - -// NewEtcd 创建 etcd server -func NewEtcd(config *EtcdConfig) (*Etcd, error) { - - var ( - e = &Etcd{} - err error - ) - - e.Endpoints = config.Endpoints - e.DialTimeout = config.DialTimeout - - e.Client, err = clientv3.New(clientv3.Config{ - Endpoints: e.Endpoints, - DialTimeout: e.DialTimeout, - }) - if err != nil { - return nil, errors.New("连接失败:" + err.Error()) - } - - // kv API子集 - e.Kv = clientv3.NewKV(e.Client) - - // 创建一个lease(租约)对象 - e.Lease = clientv3.NewLease(e.Client) - - return e, nil -} - -// Set 设置 -func (e Etcd) Set(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) { - return e.Client.Put(ctx, key, val, opts...) -} - -// Get 获取 -func (e Etcd) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) { - return e.Client.Get(ctx, key, opts...) -} - -// Del 删除 -func (e Etcd) Del(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.DeleteResponse, error) { - return e.Client.Delete(ctx, key, opts...) -} diff --git a/utils/gocache/fast.go b/utils/gocache/fast.go deleted file mode 100644 index d68a26a5..00000000 --- a/utils/gocache/fast.go +++ /dev/null @@ -1 +0,0 @@ -package gocache diff --git a/utils/gocache/free.go b/utils/gocache/free.go deleted file mode 100644 index d68a26a5..00000000 --- a/utils/gocache/free.go +++ /dev/null @@ -1 +0,0 @@ -package gocache diff --git a/utils/gocache/go.go b/utils/gocache/go.go index 5b03afdc..e2ca62cb 100644 --- a/utils/gocache/go.go +++ b/utils/gocache/go.go @@ -13,17 +13,15 @@ type GoConfig struct { // Go https://github.com/patrickmn/go-cache type Go struct { - GoConfig - db *cache.Cache // 驱动 + config *GoConfig + db *cache.Cache // 驱动 } // NewGo 实例化 func NewGo(config *GoConfig) *Go { - app := &Go{} - app.DefaultExpiration = config.DefaultExpiration - app.DefaultClear = config.DefaultClear - app.db = cache.New(app.DefaultExpiration, app.DefaultClear) - return app + c := &Go{config: config} + c.db = cache.New(c.config.DefaultExpiration, c.config.DefaultClear) + return c } // Set 插入数据 并设置过期时间 @@ -38,5 +36,5 @@ func (c *Go) Get(key string) (interface{}, bool) { // SetDefault 插入数据 并设置为默认过期时间 func (c *Go) SetDefault(key string, value interface{}) { - c.db.Set(key, value, c.DefaultExpiration) + c.db.Set(key, value, c.config.DefaultExpiration) } diff --git a/utils/gocache/go_cache.go b/utils/gocache/go_cache.go index a4090c04..a8b89648 100644 --- a/utils/gocache/go_cache.go +++ b/utils/gocache/go_cache.go @@ -11,17 +11,16 @@ type GoCacheConfig struct { // GoCache https://github.com/patrickmn/go-cache type GoCache struct { - GoCacheConfig + config *GoCacheConfig db *Go // 驱动 GetterInterface GttInterfaceFunc // 不存在的操作 } // NewCache 实例化 func (c *Go) NewCache(config *GoCacheConfig) *GoCache { - app := &GoCache{} - app.expiration = config.expiration - app.db = c - return app + cc := &GoCache{config: config} + cc.db = c + return cc } // GetInterface 缓存操作 @@ -35,7 +34,7 @@ func (gc *GoCache) GetInterface(key string) (ret interface{}) { ret, found := gc.db.Get(key) if found == false { - gc.db.Set(key, f(), gc.expiration) + gc.db.Set(key, f(), gc.config.expiration) ret, _ = gc.db.Get(key) } diff --git a/utils/gocache/group.go b/utils/gocache/group.go deleted file mode 100644 index d68a26a5..00000000 --- a/utils/gocache/group.go +++ /dev/null @@ -1 +0,0 @@ -package gocache diff --git a/utils/gocache/memcached.go b/utils/gocache/memcached.go deleted file mode 100644 index 7a9d6791..00000000 --- a/utils/gocache/memcached.go +++ /dev/null @@ -1,51 +0,0 @@ -package gocache - -import ( - "github.com/bradfitz/gomemcache/memcache" -) - -// MemcachedConfig 配置 -type MemcachedConfig struct { - Dns string // 连接地址,可选 - Db *memcache.Client // 驱动,可选 -} - -// Memcached https://github.com/bradfitz/gomemcache -type Memcached struct { - db *memcache.Client // 驱动 -} - -// NewMemcached 实例化 -func NewMemcached(config *MemcachedConfig) *Memcached { - if config.Dns == "" { - return &Memcached{db: config.Db} - } else { - mc := memcache.New(config.Dns) - if mc == nil { - panic("连接失败") - } - return &Memcached{db: mc} - } -} - -// Set 插入数据 -func (m *Memcached) Set(key string, value []byte) error { - return m.db.Set(&memcache.Item{Key: key, Value: value}) -} - -// Get 获取单个数据 -func (m *Memcached) Get(key string) (string, error) { - it, err := m.db.Get(key) - if err == memcache.ErrCacheMiss { - return "", memcache.ErrCacheMiss - } - if it.Key == key { - return string(it.Value), nil - } - return "", memcache.ErrCacheMiss -} - -// Del 删除单个数据 -func (m *Memcached) Del(key string) error { - return m.db.Delete(key) -} diff --git a/utils/gocache/memcached_cache.go b/utils/gocache/memcached_cache.go deleted file mode 100644 index 069dcf75..00000000 --- a/utils/gocache/memcached_cache.go +++ /dev/null @@ -1,57 +0,0 @@ -package gocache - -import ( - "encoding/json" - "github.com/bradfitz/gomemcache/memcache" -) - -// MemcachedCache https://github.com/bradfitz/gomemcache -type MemcachedCache struct { - db *Memcached // 驱动 - GetterString GttStringFunc // 不存在的操作 - GetterInterface GttInterfaceFunc // 不存在的操作 -} - -// NewCache 实例化 -func (m *Memcached) NewCache() *MemcachedCache { - return &MemcachedCache{db: m} -} - -// GetString 缓存操作 -func (mc *MemcachedCache) GetString(key string) (ret string) { - - f := func() string { - return mc.GetterString() - } - - // 如果不存在,则调用GetterString - ret, err := mc.db.Get(key) - - if err == memcache.ErrCacheMiss { - mc.db.Set(key, []byte(f())) - ret, _ = mc.db.Get(key) - } - - return -} - -// GetInterface 缓存操作 -func (mc *MemcachedCache) GetInterface(key string, result interface{}) { - - f := func() string { - marshal, _ := json.Marshal(mc.GetterInterface()) - return string(marshal) - } - - // 如果不存在,则调用GetterInterface - ret, err := mc.db.Get(key) - - if err == memcache.ErrCacheMiss { - mc.db.Set(key, []byte(f())) - ret, _ = mc.db.Get(key) - } - - err = json.Unmarshal([]byte(ret), result) - - return -} diff --git a/utils/gocache/redis.go b/utils/gocache/redis.go index eca74e14..580a8324 100644 --- a/utils/gocache/redis.go +++ b/utils/gocache/redis.go @@ -3,86 +3,66 @@ package gocache import ( "context" "encoding/json" - "errors" - "fmt" - "github.com/go-redis/redis/v8" + "github.com/dtapps/go-library/utils/dorm" "time" ) // RedisConfig 配置 type RedisConfig struct { - Addr string // 地址,可选 - Password string // 密码,可选 - DbName int // 数据库,可选 - DefaultExpiration time.Duration // 默认过期时间 - Db *redis.Client // 驱动,可选 + DefaultExpiration time.Duration // 默认过期时间 + Client *dorm.RedisClient // 驱动,可选 + Debug bool // 调试,可选 } // Redis https://github.com/go-redis/redis type Redis struct { - RedisConfig - db *redis.Client // 驱动 - ctx context.Context // 上下文内容 + config *RedisConfig // 配置 + Client *dorm.RedisClient // 驱动 } // NewRedis 实例化 func NewRedis(config *RedisConfig) *Redis { - app := &Redis{} - app.DefaultExpiration = config.DefaultExpiration - app.ctx = context.Background() - if config.Addr == "" { - app.db = config.Db - return app - } else { - app.db = redis.NewClient(&redis.Options{ - Addr: config.Addr, // 地址 - Password: config.Password, // 密码 - DB: config.DbName, // 数据库 - PoolSize: 100, // 连接池大小 - }) - - ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) - defer cancel() - - _, err := app.db.Ping(ctx).Result() - if err != nil { - panic(errors.New(fmt.Sprintf("连接失败,%s", err.Error()))) - } - - return app - } + c := &Redis{config: config} + c.Client = config.Client + return c } // Set 设置一个key的值 func (r *Redis) Set(key string, value interface{}, expiration time.Duration) (string, error) { - return r.db.Set(r.ctx, key, value, expiration).Result() + r.setLog(key) + return r.Client.Db.Set(context.Background(), key, value, expiration).Result() } // SetInterface 设置一个key的值 func (r *Redis) SetInterface(key string, value interface{}, expiration time.Duration) (string, error) { + r.setLog(key) marshal, _ := json.Marshal(value) - return r.db.Set(r.ctx, key, marshal, expiration).Result() + return r.Client.Db.Set(context.Background(), key, marshal, expiration).Result() } // SetDefaultExpiration 设置一个key的值,使用全局默认过期时间 func (r *Redis) SetDefaultExpiration(key string, value interface{}) (string, error) { - return r.db.Set(r.ctx, key, value, r.DefaultExpiration).Result() + r.setLog(key) + return r.Client.Db.Set(context.Background(), key, value, r.config.DefaultExpiration).Result() } // SetInterfaceDefaultExpiration 设置一个key的值,使用全局默认过期时间 func (r *Redis) SetInterfaceDefaultExpiration(key string, value interface{}) (string, error) { + r.setLog(key) marshal, _ := json.Marshal(value) - return r.db.Set(r.ctx, key, marshal, r.DefaultExpiration).Result() + return r.Client.Db.Set(context.Background(), key, marshal, r.config.DefaultExpiration).Result() } // Get 查询key的值 func (r *Redis) Get(key string) (string, error) { - return r.db.Get(r.ctx, key).Result() + r.getLog(key) + return r.Client.Db.Get(context.Background(), key).Result() } // GetInterface 查询key的值 func (r *Redis) GetInterface(key string, result interface{}) error { - ret, err := r.db.Get(r.ctx, key).Result() + r.getLog(key) + ret, err := r.Client.Db.Get(context.Background(), key).Result() if err != nil { return err } @@ -92,51 +72,52 @@ func (r *Redis) GetInterface(key string, result interface{}) error { // GetSet 设置一个key的值,并返回这个key的旧值 func (r *Redis) GetSet(key string, value interface{}) (string, error) { - return r.db.GetSet(r.ctx, key, value).Result() + return r.Client.Db.GetSet(context.Background(), key, value).Result() } // SetNX 如果key不存在,则设置这个key的值 func (r *Redis) SetNX(key string, value interface{}, expiration time.Duration) error { - return r.db.SetNX(r.ctx, key, value, expiration).Err() + return r.Client.Db.SetNX(context.Background(), key, value, expiration).Err() } // SetNXDefaultExpiration 如果key不存在,则设置这个key的值,使用全局默认过期时间 func (r *Redis) SetNXDefaultExpiration(key string, value interface{}) error { - return r.db.SetNX(r.ctx, key, value, r.DefaultExpiration).Err() + return r.Client.Db.SetNX(context.Background(), key, value, r.config.DefaultExpiration).Err() } // MGet 批量查询key的值 func (r *Redis) MGet(keys ...string) ([]interface{}, error) { - return r.db.MGet(r.ctx, keys...).Result() + return r.Client.Db.MGet(context.Background(), keys...).Result() } // MSet 批量设置key的值 // MSet(map[string]interface{}{"key1": "value1", "key2": "value2"}) func (r *Redis) MSet(values map[string]interface{}) error { - return r.db.MSet(r.ctx, values).Err() + return r.Client.Db.MSet(context.Background(), values).Err() } // Incr 针对一个key的数值进行递增操作 func (r *Redis) Incr(key string) (int64, error) { - return r.db.Incr(r.ctx, key).Result() + return r.Client.Db.Incr(context.Background(), key).Result() } // IncrBy 针对一个key的数值进行递增操作,指定每次递增多少 func (r *Redis) IncrBy(key string, value int64) (int64, error) { - return r.db.IncrBy(r.ctx, key, value).Result() + return r.Client.Db.IncrBy(context.Background(), key, value).Result() } // Decr 针对一个key的数值进行递减操作 func (r *Redis) Decr(key string) (int64, error) { - return r.db.Decr(r.ctx, key).Result() + return r.Client.Db.Decr(context.Background(), key).Result() } // DecrBy 针对一个key的数值进行递减操作,指定每次递减多少 func (r *Redis) DecrBy(key string, value int64) (int64, error) { - return r.db.DecrBy(r.ctx, key, value).Result() + return r.Client.Db.DecrBy(context.Background(), key, value).Result() } // Del 删除key操作,支持批量删除 func (r *Redis) Del(keys ...string) error { - return r.db.Del(r.ctx, keys...).Err() + r.delLog(keys...) + return r.Client.Db.Del(context.Background(), keys...).Err() } diff --git a/utils/gocache/redis_cache.go b/utils/gocache/redis_cache.go index 9416c24b..48e04bb7 100644 --- a/utils/gocache/redis_cache.go +++ b/utils/gocache/redis_cache.go @@ -12,26 +12,25 @@ type RedisCacheConfig struct { // RedisCache https://github.com/go-redis/redis type RedisCache struct { - RedisCacheConfig - db *Redis // 驱动 + config *RedisCacheConfig + operation *Redis // 操作 GetterString GttStringFunc // 不存在的操作 GetterInterface GttInterfaceFunc // 不存在的操作 } // NewCache 实例化 func (r *Redis) NewCache(config *RedisCacheConfig) *RedisCache { - app := &RedisCache{} - app.expiration = config.expiration - app.db = r - return app + c := &RedisCache{config: config} + c.operation = r + return c } // NewCacheDefaultExpiration 实例化 func (r *Redis) NewCacheDefaultExpiration() *RedisCache { - app := &RedisCache{} - app.expiration = r.DefaultExpiration - app.db = r - return app + c := &RedisCache{} + c.config.expiration = r.config.DefaultExpiration + c.operation = r + return c } // GetString 缓存操作 @@ -42,10 +41,10 @@ func (rc *RedisCache) GetString(key string) (ret string) { } // 如果不存在,则调用GetterString - ret, err := rc.db.Get(key) + ret, err := rc.operation.Get(key) if err != nil { - rc.db.Set(key, f(), rc.expiration) - ret, _ = rc.db.Get(key) + rc.operation.Set(key, f(), rc.config.expiration) + ret, _ = rc.operation.Get(key) } return @@ -60,11 +59,11 @@ func (rc *RedisCache) GetInterface(key string, result interface{}) { } // 如果不存在,则调用GetterInterface - ret, err := rc.db.Get(key) + ret, err := rc.operation.Get(key) if err != nil { - rc.db.Set(key, f(), rc.expiration) - ret, _ = rc.db.Get(key) + rc.operation.Set(key, f(), rc.config.expiration) + ret, _ = rc.operation.Get(key) } err = json.Unmarshal([]byte(ret), result) diff --git a/utils/gocache/redis_log.go b/utils/gocache/redis_log.go new file mode 100644 index 00000000..d0f5a60d --- /dev/null +++ b/utils/gocache/redis_log.go @@ -0,0 +1,19 @@ +package gocache + +import "log" + +func (r *Redis) setLog(key string) { + if r.config.Debug == true { + log.Printf("gocache [%s] set\n", key) + } +} +func (r *Redis) getLog(key string) { + if r.config.Debug == true { + log.Printf("gocache [%s] get\n", key) + } +} +func (r *Redis) delLog(key ...string) { + if r.config.Debug == true { + log.Printf("gocache [%s] del\n", key) + } +} diff --git a/utils/gocache/ristretto.go b/utils/gocache/ristretto.go deleted file mode 100644 index 308a59b2..00000000 --- a/utils/gocache/ristretto.go +++ /dev/null @@ -1,39 +0,0 @@ -package gocache - -import ( - "github.com/dgraph-io/ristretto" -) - -// Ristretto https://github.com/dgraph-io/ristretto -type Ristretto struct { - db *ristretto.Cache // 驱动 - numCounters int64 // 跟踪频率的键数 (10M) - maxCost int64 // 缓存的最大成本(1GB) - bufferItems int64 // 每个Get缓冲区的密钥数 -} - -// NewRistretto 实例化 -func NewRistretto() *Ristretto { - cache, _ := ristretto.NewCache(&ristretto.Config{ - NumCounters: 1e7, // number of keys to track frequency of (10M). - MaxCost: 1 << 30, // maximum cost of cache (1GB). - BufferItems: 64, // number of keys per Get buffer. - }) - return &Ristretto{db: cache} -} - -// Set 插入数据 -func (r *Ristretto) Set(key string, value interface{}, cost int64) { - r.db.Set(key, value, cost) - r.db.Wait() -} - -// Get 获取单个数据 -func (r *Ristretto) Get(key string) (interface{}, bool) { - return r.db.Get(key) -} - -// Del 删除数据 -func (r *Ristretto) Del(key string) { - r.db.Del(key) -} diff --git a/utils/gocache/ristretto_cache.go b/utils/gocache/ristretto_cache.go deleted file mode 100644 index 87ecedac..00000000 --- a/utils/gocache/ristretto_cache.go +++ /dev/null @@ -1,30 +0,0 @@ -package gocache - -// RistrettoCache https://github.com/dgraph-io/ristretto -type RistrettoCache struct { - db *Ristretto // 驱动 - GetterInterface GttInterfaceFunc // 不存在的操作 -} - -// NewCache 实例化 -func (r *Ristretto) NewCache() *RistrettoCache { - return &RistrettoCache{db: r} -} - -// GetInterface 缓存操作 -func (rc *RistrettoCache) GetInterface(key string) (ret interface{}) { - - f := func() interface{} { - return rc.GetterInterface() - } - - // 如果不存在,则调用GetterInterface - ret, found := rc.db.Get(key) - - if found == false { - rc.db.Set(key, f(), 1) - ret, _ = rc.db.Get(key) - } - - return -} diff --git a/utils/goip/ip.go b/utils/goip/ip.go index 4f553afb..2593c612 100644 --- a/utils/goip/ip.go +++ b/utils/goip/ip.go @@ -1,13 +1,14 @@ package goip import ( + "context" "encoding/json" "github.com/dtapps/go-library/utils/gorequest" "net" ) // GetInsideIp 内网ip -func GetInsideIp() string { +func GetInsideIp(ctx context.Context) string { conn, err := net.Dial("udp", "8.8.8.8:80") if err != nil { panic(err) @@ -19,7 +20,7 @@ func GetInsideIp() string { } // Ips 获取全部网卡的全部IP -func Ips() (map[string]string, error) { +func Ips(ctx context.Context) (map[string]string, error) { ips := make(map[string]string) @@ -53,11 +54,11 @@ var respGetOutsideIp struct { } // GetOutsideIp 外网ip -func GetOutsideIp() (ip string) { +func GetOutsideIp(ctx context.Context) (ip string) { ip = "0.0.0.0" get := gorequest.NewHttp() get.SetUri("https://api.dtapp.net/ip") - response, err := get.Get() + response, err := get.Get(ctx) if err != nil { return } @@ -73,7 +74,7 @@ func GetOutsideIp() (ip string) { } // GetMacAddr 获取Mac地址 -func GetMacAddr() (arrays []string) { +func GetMacAddr(ctx context.Context) (arrays []string) { netInterfaces, err := net.Interfaces() if err != nil { return arrays diff --git a/utils/goip/v4/qqwry.dat b/utils/goip/v4/qqwry.dat index 0d221437..cf90f84a 100644 Binary files a/utils/goip/v4/qqwry.dat and b/utils/goip/v4/qqwry.dat differ diff --git a/utils/gojobs/etcd.go b/utils/gojobs/etcd.go deleted file mode 100644 index d2d4469a..00000000 --- a/utils/gojobs/etcd.go +++ /dev/null @@ -1,64 +0,0 @@ -package gojobs - -import ( - "go.etcd.io/etcd/client/v3" - "time" -) - -// EtcdConfig etcd配置 -type EtcdConfig struct { - Endpoints []string // 接口 []string{"http://127.0.0.1:2379"} - DialTimeout time.Duration // time.Second * 5 - LocalIP string // 本机IP - Username string // 用户名 - Password string // 密码 - CustomDirectory string // 自定义目录,后面不需要/ - Debug bool // 是否打印 -} - -// Etcd etcd -type Etcd struct { - EtcdConfig // 配置 - Client *clientv3.Client // 驱动 - Kv clientv3.KV // kv API子集 - Lease clientv3.Lease // lease(租约)对象 - leaseId clientv3.LeaseID // 租约编号 -} - -// Close 关闭 -func (e Etcd) Close() { - e.Client.Close() -} - -const ( - // JobSaveDir 定时任务任务保存目录 - JobSaveDir = "/cron/jobs/" - // JobWorkerDir 服务注册目录 - JobWorkerDir = "/cron/workers/" -) - -func getJobSaveDir(e Etcd) string { - if e.CustomDirectory == "" { - return JobSaveDir - } else { - return JobSaveDir + e.CustomDirectory + "/" - } -} - -func getJobWorkerDir(e Etcd) string { - if e.CustomDirectory == "" { - return JobWorkerDir - } else { - return JobWorkerDir + e.CustomDirectory + "/" - } -} - -// GetWatchKey 监听的key -func (e Etcd) GetWatchKey() string { - return getJobSaveDir(e) + e.LocalIP -} - -// IssueWatchKey 下发的key -func (e Etcd) IssueWatchKey(ip string) string { - return getJobSaveDir(e) + ip -} diff --git a/utils/gojobs/etcd_curd.go b/utils/gojobs/etcd_curd.go deleted file mode 100644 index ffc3af18..00000000 --- a/utils/gojobs/etcd_curd.go +++ /dev/null @@ -1,31 +0,0 @@ -package gojobs - -import ( - "context" - "go.etcd.io/etcd/client/v3" -) - -// Watch 监听 -func (e Etcd) Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan { - return e.Client.Watch(ctx, key, opts...) -} - -// Create 创建 -func (e Etcd) Create(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) { - return e.Client.Put(ctx, key, val, opts...) -} - -// Get 获取 -func (e Etcd) Get(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.GetResponse, error) { - return e.Client.Get(ctx, key, opts...) -} - -// Update 更新 -func (e Etcd) Update(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) { - return e.Client.Put(ctx, key, val, opts...) -} - -// Delete 删除 -func (e Etcd) Delete(ctx context.Context, key string, opts ...clientv3.OpOption) (*clientv3.DeleteResponse, error) { - return e.Client.Delete(ctx, key, opts...) -} diff --git a/utils/gojobs/etcd_server.go b/utils/gojobs/etcd_server.go deleted file mode 100644 index 57a803f6..00000000 --- a/utils/gojobs/etcd_server.go +++ /dev/null @@ -1,82 +0,0 @@ -package gojobs - -import ( - "context" - "errors" - "go.etcd.io/etcd/api/v3/mvccpb" - "go.etcd.io/etcd/client/v3" - "strings" -) - -// NewEtcdServer 创建 etcd server -func NewEtcdServer(config *EtcdConfig) (*Etcd, error) { - - var ( - e = &Etcd{} - err error - ) - - e.Endpoints = config.Endpoints - e.DialTimeout = config.DialTimeout - e.LocalIP = config.LocalIP - e.Username = config.Username - e.Password = config.Password - e.CustomDirectory = config.CustomDirectory - - e.Debug = config.Debug - - v3Config := clientv3.Config{ - Endpoints: e.Endpoints, - DialTimeout: e.DialTimeout, - } - - // 判断有没有配置用户信息 - if e.Username != "" { - v3Config.Username = e.Username - v3Config.Password = e.Password - } - - e.Client, err = clientv3.New(v3Config) - if err != nil { - return nil, errors.New("连接失败:" + err.Error()) - } - - // kv API子集 - e.Kv = clientv3.NewKV(e.Client) - - // 创建一个lease(租约)对象 - e.Lease = clientv3.NewLease(e.Client) - - return e, nil -} - -// ListWorkers 获取在线worker列表 -func (e Etcd) ListWorkers() (workerArr []string, err error) { - var ( - getResp *clientv3.GetResponse - kv *mvccpb.KeyValue - workerIP string - ) - - // 初始化数组 - workerArr = make([]string, 0) - - // 获取目录下所有Kv - getResp, err = e.Kv.Get(context.TODO(), getJobWorkerDir(e), clientv3.WithPrefix()) - if err != nil { - return workerArr, err - } - - // 解析每个节点的IP - for _, kv = range getResp.Kvs { - // kv.Key : /cron/workers/192.168.2.1 - workerIP = e.ExtractWorkerIP(string(kv.Key)) - workerArr = append(workerArr, workerIP) - } - return workerArr, err -} - -// ExtractWorkerIP 提取worker的IP -func (e Etcd) ExtractWorkerIP(regKey string) string { - return strings.TrimPrefix(regKey, getJobWorkerDir(e)) -} diff --git a/utils/gojobs/etcd_worker.go b/utils/gojobs/etcd_worker.go deleted file mode 100644 index 1ebaab77..00000000 --- a/utils/gojobs/etcd_worker.go +++ /dev/null @@ -1,136 +0,0 @@ -package gojobs - -import ( - "context" - "errors" - "fmt" - "go.etcd.io/etcd/client/v3" - "log" - "time" -) - -// NewEtcdWorker 创建 etcd Worker -func NewEtcdWorker(config *EtcdConfig) (*Etcd, error) { - - var ( - e = &Etcd{} - err error - ) - - e.Endpoints = config.Endpoints - e.DialTimeout = config.DialTimeout - if config.LocalIP == "" { - return nil, errors.New("需要配置客户端的ip地址,唯一性~!") - } - e.LocalIP = config.LocalIP - e.Username = config.Username - e.Password = config.Password - e.CustomDirectory = config.CustomDirectory - - e.Debug = config.Debug - - v3Config := clientv3.Config{ - Endpoints: e.Endpoints, - DialTimeout: e.DialTimeout, - } - - // 判断有没有配置用户信息 - if e.Username != "" { - v3Config.Username = e.Username - v3Config.Password = e.Password - } - - e.Client, err = clientv3.New(v3Config) - if err != nil { - return nil, errors.New("连接失败:" + err.Error()) - } - - // 获得kv API子集 - e.Kv = clientv3.NewKV(e.Client) - - // 创建一个lease(租约)对象 - e.Lease = clientv3.NewLease(e.Client) - - // 注册服务 - go e.RegisterWorker() - - return e, nil -} - -// RegisterWorker 注册worker -func (e Etcd) RegisterWorker() { - var ( - regKey string - leaseGrantResp *clientv3.LeaseGrantResponse - err error - keepAliveChan <-chan *clientv3.LeaseKeepAliveResponse - keepAliveResp *clientv3.LeaseKeepAliveResponse - cancelCtx context.Context - cancelFunc context.CancelFunc - ) - - for { - // 注册路径 - regKey = getJobWorkerDir(e) + e.LocalIP - if e.Debug == true { - log.Println("租约:", regKey) - } - - cancelFunc = nil - - // 申请一个10秒的租约 - leaseGrantResp, err = e.Lease.Grant(context.TODO(), 10) - if err != nil { - if e.Debug == true { - log.Println("申请一个10秒的租约失败", err) - } - goto RETRY - } - - // 自动永久续租 - keepAliveChan, err = e.Lease.KeepAlive(context.TODO(), leaseGrantResp.ID) - if err != nil { - if e.Debug == true { - log.Println("自动永久续租失败", err) - } - goto RETRY - } - - cancelCtx, cancelFunc = context.WithCancel(context.TODO()) - - // 注册到etcd - _, err = e.Kv.Put(cancelCtx, regKey, "", clientv3.WithLease(leaseGrantResp.ID)) - if err != nil { - if e.Debug == true { - log.Println(fmt.Sprintf(" %s 服务注册失败:%s", regKey, err)) - } - goto RETRY - } - - // 处理续约应答的协程 - for { - select { - case keepAliveResp = <-keepAliveChan: - if keepAliveResp == nil { - if e.Debug == true { - log.Println("续租失败") - } - goto RETRY - } else { - if e.Debug == true { - log.Println("收到自动续租应答:", leaseGrantResp.ID) - } - } - } - } - - RETRY: - if e.Debug == true { - log.Println("异常 RETRY ", regKey) - } - time.Sleep(1 * time.Second) - if cancelFunc != nil { - cancelFunc() - } - } -} diff --git a/utils/gojobs/grpc.go b/utils/gojobs/grpc.go index 5c6b6411..aec407e5 100644 --- a/utils/gojobs/grpc.go +++ b/utils/gojobs/grpc.go @@ -1,6 +1,7 @@ package gojobs import ( + "context" "fmt" "github.com/dtapps/go-library/utils/goip" ) @@ -8,7 +9,7 @@ import ( var ip string func configIp() { - ip = goip.GetOutsideIp() + ip = goip.GetOutsideIp(context.Background()) } const prefix = "cron:" diff --git a/utils/gojobs/grpc_worker.go b/utils/gojobs/grpc_worker.go index 7ba258f2..65aea385 100644 --- a/utils/gojobs/grpc_worker.go +++ b/utils/gojobs/grpc_worker.go @@ -3,7 +3,7 @@ package gojobs import ( "context" "github.com/dtapps/go-library/utils/gojobs/pb" - "github.com/dtapps/go-library/utils/only" + "github.com/dtapps/go-library/utils/gostring" "google.golang.org/grpc" ) @@ -52,7 +52,7 @@ func NewWorker(config *WorkerConfig) *Worker { // SubscribeCron 订阅服务 func (w *Worker) SubscribeCron() pb.PubSub_SubscribeClient { stream, err := w.Pub.Subscribe(context.Background(), &pb.SubscribeRequest{ - Id: only.GetUuId(), + Id: gostring.GetUuId(), Value: prefix, Ip: w.ClientIp, }) @@ -65,7 +65,7 @@ func (w *Worker) SubscribeCron() pb.PubSub_SubscribeClient { // StartCron 启动任务 func (w *Worker) StartCron() pb.PubSub_SubscribeClient { stream, err := w.Pub.Subscribe(context.Background(), &pb.SubscribeRequest{ - Id: only.GetUuId(), + Id: gostring.GetUuId(), Value: prefixSprintf(w.ClientIp), Ip: w.ClientIp, }) diff --git a/utils/gojobs/jobs_beego_orm.go b/utils/gojobs/jobs_beego_orm.go deleted file mode 100644 index d2beebb2..00000000 --- a/utils/gojobs/jobs_beego_orm.go +++ /dev/null @@ -1,15 +0,0 @@ -package gojobs - -import "github.com/beego/beego/v2/client/orm" - -type JobsBeegoOrm struct { - Db *orm.Ormer -} - -func NewJobsBeegoOrm(db *orm.Ormer) *JobsBeegoOrm { - var ( - jobsBeegoOrm = &JobsBeegoOrm{} - ) - jobsBeegoOrm.Db = db - return jobsBeegoOrm -} diff --git a/utils/gojobs/jobs_beego_orm_model/task.go b/utils/gojobs/jobs_beego_orm_model/task.go deleted file mode 100644 index ce52715a..00000000 --- a/utils/gojobs/jobs_beego_orm_model/task.go +++ /dev/null @@ -1,28 +0,0 @@ -package jobs_beego_orm_model - -// Task 任务 -type Task struct { - Id uint `orm:"auto" json:"id"` // 记录编号 - Status string `json:"status"` // 状态码 - Params string `json:"params"` // 参数 - ParamsType string `json:"params_type"` // 参数类型 - StatusDesc string `json:"status_desc"` // 状态描述 - Frequency int64 `json:"frequency"` // 频率(秒单位) - Number int64 `json:"number"` // 当前次数 - MaxNumber int64 `json:"max_number"` // 最大次数 - RunId string `json:"run_id"` // 执行编号 - CustomId string `json:"custom_id"` // 自定义编号 - CustomSequence int64 `json:"custom_sequence"` // 自定义顺序 - Type string `json:"type"` // 类型 - CreatedIp string `json:"created_ip"` // 创建外网IP - SpecifyIp string `json:"specify_ip"` // 指定外网IP - UpdatedIp string `json:"updated_ip"` // 更新外网IP - Result string `json:"result"` // 结果 - CreatedAt string `orm:"auto_now_add;type(text)" json:"created_at"` // 创建时间 - UpdatedAt string `orm:"auto_now;type(text)" json:"updated_at"` // 更新时间 - DeletedAt string `orm:"on_delete(set_null)" json:"deleted_at"` // 删除时间 -} - -func (m *Task) TableName() string { - return "task" -} diff --git a/utils/gojobs/jobs_beego_orm_model/task_ip.go b/utils/gojobs/jobs_beego_orm_model/task_ip.go deleted file mode 100644 index a97a1e2c..00000000 --- a/utils/gojobs/jobs_beego_orm_model/task_ip.go +++ /dev/null @@ -1,12 +0,0 @@ -package jobs_beego_orm_model - -// TaskIp 任务Ip -type TaskIp struct { - Id int64 `orm:"auto" json:"id"` - TaskType string `json:"task_type"` // 任务编号 - Ips string `json:"ips"` // 任务IP -} - -func (m *TaskIp) TableName() string { - return "task_ip" -} diff --git a/utils/gojobs/jobs_beego_orm_model/task_log.go b/utils/gojobs/jobs_beego_orm_model/task_log.go deleted file mode 100644 index 74cf5958..00000000 --- a/utils/gojobs/jobs_beego_orm_model/task_log.go +++ /dev/null @@ -1,15 +0,0 @@ -package jobs_beego_orm_model - -// TaskLog 任务日志模型 -type TaskLog struct { - Id uint `orm:"auto" json:"id"` // 记录编号 - TaskId uint `json:"task_id"` // 任务编号 - StatusCode int `json:"status_code"` // 状态码 - Desc string `json:"desc"` // 结果 - Version int `json:"version"` // 版本 - CreatedAt string `orm:"auto_now_add;type(text)" json:"created_at"` // 创建时间 -} - -func (m *TaskLog) TableName() string { - return "task_log" -} diff --git a/utils/gojobs/jobs_beego_orm_model/task_log_run.go b/utils/gojobs/jobs_beego_orm_model/task_log_run.go deleted file mode 100644 index e3037dae..00000000 --- a/utils/gojobs/jobs_beego_orm_model/task_log_run.go +++ /dev/null @@ -1,20 +0,0 @@ -package jobs_beego_orm_model - -// TaskLogRun 任务执行日志模型 -type TaskLogRun struct { - Id uint `orm:"auto" json:"id"` // 记录编号 - TaskId uint `json:"task_id"` // 任务编号 - RunId string `json:"run_id"` // 执行编号 - OutsideIp string `json:"outside_ip"` // 外网ip - InsideIp string `json:"inside_ip"` // 内网ip - Os string `json:"os"` // 系统类型 - Arch string `json:"arch"` // 系统架构 - Gomaxprocs int `json:"gomaxprocs"` // CPU核数 - GoVersion string `json:"go_version"` // GO版本 - MacAddrs string `json:"mac_addrs"` // Mac地址 - CreatedAt string `orm:"auto_now_add;type(text)" json:"created_at"` // 创建时间 -} - -func (m *TaskLogRun) TableName() string { - return "task_log_run" -} diff --git a/utils/gojobs/jobs_gorm.go b/utils/gojobs/jobs_gorm.go index 2847bc32..185e8463 100644 --- a/utils/gojobs/jobs_gorm.go +++ b/utils/gojobs/jobs_gorm.go @@ -1,109 +1,102 @@ package gojobs import ( + "context" "errors" "fmt" "github.com/dtapps/go-library" + "github.com/dtapps/go-library/utils/dorm" "github.com/dtapps/go-library/utils/goarray" "github.com/dtapps/go-library/utils/goip" "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" "github.com/dtapps/go-library/utils/golock" - "github.com/go-redis/redis/v8" - "go.etcd.io/etcd/client/v3" - "gorm.io/gorm" + "log" "runtime" ) +type JobsGormConfig struct { + GormClient *dorm.GormClient // 数据库驱动 + RedisClient *dorm.RedisClient // 缓存数据库驱动 + CurrentIp string // 当前ip + LockKeyPrefix string // 锁Key前缀 xxx_lock + LockKeySeparator string // 锁Key分隔符 : + CornKeyPrefix string // 任务Key前缀 xxx_cron + CornKeyCustom string // 任务Key自定义 xxx_cron_自定义 xxx_cron_自定义_* + Debug bool // 调试 +} + // JobsGorm Gorm数据库驱动 type JobsGorm struct { - db struct { - gormClient *gorm.DB // 数据库驱动 - redisClient *redis.Client // 缓存数据库驱动 - etcdClient *clientv3.Client // 分布式缓存驱动 + gormClient *dorm.GormClient // 数据库驱动 + redisClient *dorm.RedisClient // 缓存驱动 + lockClient *golock.LockRedis // 锁驱动 + config struct { + debug bool // 调试 + runVersion string // 运行版本 + os string // 系统类型 + arch string // 系统架构 + maxProCs int // CPU核数 + version string // GO版本 + macAddrS string // Mac地址 + insideIp string // 内网ip + outsideIp string // 外网ip + lockKeyPrefix string // 锁Key前缀 xxx_lock + lockKeySeparator string // 锁Key分隔符 : + cornKeyPrefix string // 任务Key前缀 xxx_cron + cornKeyCustom string // 任务Key自定义 } - service struct { - gormClient *gorm.DB // 数据库驱动 - lockRedisClient *golock.LockRedis // 缓存数据库驱动 - lockEtcdClient *golock.LockEtcd // 分布式缓存驱动 - } // 服务 - config struct { - lockPrefix string // 锁Key前缀 - lockType string // 锁驱动类型 - runVersion string // 运行版本 - os string // 系统类型 - arch string // 系统架构 - maxProCs int // CPU核数 - version string // GO版本 - macAddrS string // Mac地址 - insideIp string // 内网ip - outsideIp string // 外网ip - } // 配置 } // NewJobsGorm 初始化 -// WithGormClient && WithRedisClient && WithLockPrefix && WithOutsideIp -// WithGormClient && WithEtcdClient && WithLockPrefix && WithOutsideIp -func NewJobsGorm(attrs ...*OperationAttr) (*JobsGorm, error) { +func NewJobsGorm(config *JobsGormConfig) (*JobsGorm, error) { - c := &JobsGorm{} - for _, attr := range attrs { - if attr.gormClient != nil { - c.db.gormClient = attr.gormClient - c.service.gormClient = attr.gormClient - } - if attr.redisClient != nil { - c.db.redisClient = attr.redisClient - c.config.lockType = attr.lockType - } - if attr.etcdClient != nil { - c.db.etcdClient = attr.etcdClient - c.config.lockType = attr.lockType - } - if attr.lockPrefix != "" { - c.config.lockPrefix = attr.lockPrefix - } - if attr.outsideIp != "" { - c.config.outsideIp = attr.outsideIp - } + // 判断 + if config.LockKeyPrefix == "" { + return nil, errors.New("需要配置锁Key前缀") } - - if c.config.outsideIp == "" { + if config.LockKeySeparator == "" { + return nil, errors.New("需要配置锁Key分隔符") + } + if config.CornKeyPrefix == "" { + return nil, errors.New("需要配置任务Key前缀") + } + if config.CornKeyCustom == "" { + return nil, errors.New("需要配置任务Key自定义") + } + if config.CurrentIp == "" { return nil, errors.New("需要配置当前的IP") } - - if c.db.gormClient == nil { + if config.GormClient == nil { return nil, errors.New("需要配置数据库驱动") } + if config.RedisClient == nil { + return nil, errors.New("需要配置缓存数据库驱动") + } + + c := &JobsGorm{} + c.gormClient = config.GormClient + c.redisClient = config.RedisClient + c.config.outsideIp = config.CurrentIp + c.config.lockKeyPrefix = config.LockKeyPrefix + c.config.lockKeySeparator = config.LockKeySeparator + c.config.cornKeyPrefix = config.CornKeyPrefix + c.config.cornKeyCustom = config.CornKeyCustom + c.config.debug = config.Debug + + // 锁 + c.lockClient = golock.NewLockRedis(c.redisClient) + // 配置信息 c.config.runVersion = go_library.Version() c.config.os = runtime.GOOS c.config.arch = runtime.GOARCH c.config.maxProCs = runtime.GOMAXPROCS(0) c.config.version = runtime.Version() - c.config.macAddrS = goarray.TurnString(goip.GetMacAddr()) - c.config.insideIp = goip.GetInsideIp() - - switch c.config.lockType { - case lockTypeRedis: - - if c.db.redisClient == nil { - return nil, errors.New("没有设置REDIS驱动") - } - c.service.lockRedisClient = golock.NewLockRedis(c.db.redisClient) - - case lockTypeEtcd: + c.config.macAddrS = goarray.TurnString(goip.GetMacAddr(context.Background())) + c.config.insideIp = goip.GetInsideIp(context.Background()) - if c.db.etcdClient == nil { - return nil, errors.New("没有设置ETCD驱动") - } - c.service.lockEtcdClient = golock.NewLockEtcd(c.db.etcdClient) - - default: - // 添加任务端不需要 - // return nil, errors.New("驱动为空") - } - - err := c.service.gormClient.AutoMigrate( + // 创建模型 + err := c.gormClient.Db.AutoMigrate( &jobs_gorm_model.Task{}, &jobs_gorm_model.TaskLog{}, &jobs_gorm_model.TaskLogRun{}, @@ -113,5 +106,9 @@ func NewJobsGorm(attrs ...*OperationAttr) (*JobsGorm, error) { return nil, errors.New(fmt.Sprintf("创建任务模型失败:%v\n", err)) } + if c.config.debug == true { + log.Printf("JOBS配置:%+v\n", c.config) + } + return c, nil } diff --git a/utils/gojobs/jobs_gorm_check_task.go b/utils/gojobs/jobs_gorm_check_task.go index 66321e58..8500685a 100644 --- a/utils/gojobs/jobs_gorm_check_task.go +++ b/utils/gojobs/jobs_gorm_check_task.go @@ -13,10 +13,12 @@ func (j *JobsGorm) CheckManyTask(tx *gorm.DB, vs []jobs_gorm_model.Task) { for _, v := range vs { diffInSecondWithAbs := gotime.Current().DiffInSecondWithAbs(gotime.SetCurrent(v.UpdatedAt).Time) if diffInSecondWithAbs >= v.Frequency*3 { - log.Printf("每隔%v秒任务:%v相差%v秒\n", v.Frequency, v.Id, diffInSecondWithAbs) - statusDelete := tx.Where("task_id = ?", v.Id).Where("run_id = ?", v.RunId).Delete(&jobs_gorm_model.TaskLogRun{}) - if statusDelete.RowsAffected == 0 { - log.Println("删除失败", statusDelete.Error) + if j.config.debug == true { + log.Printf("每隔%v秒任务:%v相差%v秒\n", v.Frequency, v.Id, diffInSecondWithAbs) + } + err := tx.Where("task_id = ?", v.Id).Where("run_id = ?", v.RunId).Delete(&jobs_gorm_model.TaskLogRun{}).Error + if err != nil { + log.Println("删除失败", err.Error()) } } } @@ -27,10 +29,12 @@ func (j *JobsGorm) CheckManyTask(tx *gorm.DB, vs []jobs_gorm_model.Task) { func (j *JobsGorm) CheckSingleTask(tx *gorm.DB, v jobs_gorm_model.Task) { diffInSecondWithAbs := gotime.Current().DiffInSecondWithAbs(gotime.SetCurrent(v.UpdatedAt).Time) if diffInSecondWithAbs >= v.Frequency*3 { - log.Printf("每隔%v秒任务:%v相差%v秒\n", v.Frequency, v.Id, diffInSecondWithAbs) - statusDelete := tx.Where("task_id = ?", v.Id).Where("run_id = ?", v.RunId).Delete(&jobs_gorm_model.TaskLogRun{}) - if statusDelete.RowsAffected == 0 { - log.Println("删除失败", statusDelete.Error) + if j.config.debug == true { + log.Printf("每隔%v秒任务:%v相差%v秒\n", v.Frequency, v.Id, diffInSecondWithAbs) + } + err := tx.Where("task_id = ?", v.Id).Where("run_id = ?", v.RunId).Delete(&jobs_gorm_model.TaskLogRun{}).Error + if err != nil { + log.Println("删除失败", err.Error()) } } } diff --git a/utils/gojobs/jobs_gorm_etcd.go b/utils/gojobs/jobs_gorm_etcd.go deleted file mode 100644 index 00317f32..00000000 --- a/utils/gojobs/jobs_gorm_etcd.go +++ /dev/null @@ -1,70 +0,0 @@ -package gojobs - -import ( - "errors" - "fmt" - "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" - "math/rand" - "time" -) - -// GetEtcdIssueAddress 获取ETCD下发地址 -func (j *JobsGorm) GetEtcdIssueAddress(server *Etcd, v *jobs_gorm_model.Task) (address string, err error) { - var ( - currentIp = "" // 当前Ip - appointIpStatus = false // 指定Ip状态 - ) - - // 赋值ip - if v.SpecifyIp != "" { - currentIp = v.SpecifyIp - appointIpStatus = true - } - - workers, err := server.ListWorkers() - if err != nil { - return address, errors.New(fmt.Sprintf("获取在线客户端列表失败:%s", err.Error())) - } - if len(workers) <= 0 { - return address, errors.New("没有客户端在线") - } - - // 只有一个客户端在线 - if len(workers) == 1 { - if appointIpStatus == true { - // 判断是否指定某ip执行 - if currentIp == workers[0] { - return fmt.Sprintf("%s/%d", server.IssueWatchKey(v.SpecifyIp), v.Id), nil - } - return address, errors.New("执行的客户端不在线") - } - return fmt.Sprintf("%s/%d", server.IssueWatchKey(workers[0]), v.Id), nil - } - - // 优先处理指定某ip执行 - if appointIpStatus == true { - for _, wv := range workers { - if currentIp == wv { - return fmt.Sprintf("%s/%d", server.IssueWatchKey(wv), v.Id), nil - } - } - return address, errors.New("执行的客户端不在线") - } else { - // 随机返回一个 - zxIp := workers[j.random(0, len(workers))] - if zxIp == "" { - return address, errors.New("获取执行的客户端异常") - } - address = fmt.Sprintf("%s/%d", server.IssueWatchKey(zxIp), v.Id) - return address, err - } -} - -// 随机返回一个 -func (j *JobsGorm) random(min, max int) int { - if max-min <= 0 { - return 0 - } - rand.Seed(time.Now().Unix()) - return rand.Intn(max-min) + min -} diff --git a/utils/gojobs/jobs_gorm_get.go b/utils/gojobs/jobs_gorm_get.go index db4c67aa..0335cb42 100644 --- a/utils/gojobs/jobs_gorm_get.go +++ b/utils/gojobs/jobs_gorm_get.go @@ -1,22 +1,21 @@ package gojobs import ( - "github.com/go-redis/redis/v8" - "go.etcd.io/etcd/client/v3" + "github.com/go-redis/redis/v9" "gorm.io/gorm" ) -// GetDb 数据库驱动 +// GetDb 获取数据库驱动 func (j *JobsGorm) GetDb() *gorm.DB { - return j.service.gormClient + return j.gormClient.Db } -// GetRedis 缓存数据库驱动 +// GetRedis 获取缓存数据库驱动 func (j *JobsGorm) GetRedis() *redis.Client { - return j.db.redisClient + return j.redisClient.Db } -// GetEtcd 分布式缓存驱动 -func (j *JobsGorm) GetEtcd() *clientv3.Client { - return j.db.etcdClient +// GetCurrentIp 获取当前ip +func (j *JobsGorm) GetCurrentIp() string { + return j.config.outsideIp } diff --git a/utils/gojobs/jobs_gorm_ip.go b/utils/gojobs/jobs_gorm_ip.go index 765c3d12..89da3653 100644 --- a/utils/gojobs/jobs_gorm_ip.go +++ b/utils/gojobs/jobs_gorm_ip.go @@ -1,14 +1,15 @@ package gojobs import ( + "context" "github.com/dtapps/go-library/utils/goip" "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" "gorm.io/gorm" ) // RefreshIp 刷新Ip -func (j *JobsGorm) RefreshIp(tx *gorm.DB) { - xip := goip.GetOutsideIp() +func (j *JobsGorm) RefreshIp(ctx context.Context, tx *gorm.DB) { + xip := goip.GetOutsideIp(ctx) if j.config.outsideIp == "" || j.config.outsideIp == "0.0.0.0" { return } diff --git a/utils/gojobs/jobs_gorm_lock.go b/utils/gojobs/jobs_gorm_lock.go index 483f94fa..96e90a15 100644 --- a/utils/gojobs/jobs_gorm_lock.go +++ b/utils/gojobs/jobs_gorm_lock.go @@ -1,67 +1,22 @@ package gojobs import ( - "errors" "fmt" "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" + "time" ) // Lock 上锁 func (j *JobsGorm) Lock(info jobs_gorm_model.Task, id any) (string, error) { - - if j.config.lockType == "" { - return "", errors.New("没有配置") - } - - var ( - redisKey = fmt.Sprintf("%s:%v:%v", j.config.lockPrefix, info.Type, id) - etcdKey = fmt.Sprintf("%s/%v/%v", j.config.lockPrefix, info.Type, id) - val = fmt.Sprintf("已在%s@%s机器上锁成功", j.config.insideIp, j.config.outsideIp) - ttl = info.Frequency * 3 - ) - - if j.config.lockType == lockTypeRedis { - return j.service.lockRedisClient.Lock(redisKey, val, ttl) - } - - return j.service.lockEtcdClient.Lock(etcdKey, val, ttl) + return j.lockClient.Lock(fmt.Sprintf("%s%s%v%s%v", j.config.lockKeyPrefix, j.config.lockKeySeparator, info.Type, j.config.lockKeySeparator, id), fmt.Sprintf("已在%s@%s机器上锁成功", j.config.insideIp, j.config.outsideIp), time.Duration(info.Frequency)*3*time.Second) } // Unlock Lock 解锁 func (j *JobsGorm) Unlock(info jobs_gorm_model.Task, id any) error { - - if j.config.lockType == "" { - return errors.New("没有配置") - } - - var ( - redisKey = fmt.Sprintf("%s:%v:%v", j.config.lockPrefix, info.Type, id) - etcdKey = fmt.Sprintf("%s/%v/%v", j.config.lockPrefix, info.Type, id) - ) - - if j.config.lockType == lockTypeRedis { - return j.service.lockRedisClient.Unlock(redisKey) - } - - return j.service.lockEtcdClient.Unlock(etcdKey) + return j.lockClient.Unlock(fmt.Sprintf("%s%s%v%s%v", j.config.lockKeyPrefix, j.config.lockKeySeparator, info.Type, j.config.lockKeySeparator, id)) } // LockForever 永远上锁 func (j *JobsGorm) LockForever(info jobs_gorm_model.Task, id any) (string, error) { - - if j.config.lockType == "" { - return "", errors.New("没有配置") - } - - var ( - redisKey = fmt.Sprintf("%s:%v:%v", j.config.lockPrefix, info.Type, id) - etcdKey = fmt.Sprintf("%s/%v/%v", j.config.lockPrefix, info.Type, id) - val = fmt.Sprintf("已在%s@%s机器永远上锁成功", j.config.insideIp, j.config.outsideIp) - ) - - if j.config.lockType == lockTypeRedis { - return j.service.lockRedisClient.LockForever(redisKey, val) - } - - return j.service.lockEtcdClient.LockForever(etcdKey, val) + return j.lockClient.LockForever(fmt.Sprintf("%s%s%v%s%v", j.config.lockKeyPrefix, j.config.lockKeySeparator, info.Type, j.config.lockKeySeparator, id), fmt.Sprintf("已在%s@%s机器永远上锁成功", j.config.insideIp, j.config.outsideIp)) } diff --git a/utils/gojobs/jobs_gorm_model/task.go b/utils/gojobs/jobs_gorm_model/task.go index 582830bc..70231ae5 100644 --- a/utils/gojobs/jobs_gorm_model/task.go +++ b/utils/gojobs/jobs_gorm_model/task.go @@ -19,6 +19,7 @@ type Task struct { CustomId string `gorm:"index;comment:自定义编号" json:"custom_id"` // 自定义编号 CustomSequence int64 `gorm:"index;comment:自定义顺序" json:"custom_sequence"` // 自定义顺序 Type string `gorm:"index;comment:类型" json:"type"` // 类型 + TypeName string `gorm:"comment:类型名称" json:"type_name"` // 类型名称 CreatedIp string `gorm:"comment:创建外网IP" json:"created_ip"` // 创建外网IP SpecifyIp string `gorm:"index;comment:指定外网IP" json:"specify_ip"` // 指定外网IP UpdatedIp string `gorm:"comment:更新外网IP" json:"updated_ip"` // 更新外网IP diff --git a/utils/gojobs/jobs_gorm_redis.go b/utils/gojobs/jobs_gorm_redis.go new file mode 100644 index 00000000..08ff7209 --- /dev/null +++ b/utils/gojobs/jobs_gorm_redis.go @@ -0,0 +1,38 @@ +package gojobs + +import ( + "context" + "github.com/go-redis/redis/v9" + "log" +) + +// Publish 发布 +// ctx 上下文 +// channel 频道 +// message 消息 +func (j *JobsGorm) Publish(ctx context.Context, channel string, message interface{}) error { + publish, err := j.redisClient.Publish(ctx, channel, message).Result() + if j.config.debug == true { + log.Println("gojobs.Publish", channel, message, publish, err) + } + return err +} + +type SubscribeResult struct { + err error + Message *redis.PubSub +} + +// Subscribe 订阅 +func (j *JobsGorm) Subscribe(ctx context.Context) SubscribeResult { + return SubscribeResult{ + Message: j.redisClient.Subscribe(ctx, j.config.cornKeyPrefix+"_"+j.config.cornKeyCustom), + } +} + +// PSubscribe 订阅,支持通配符匹配(ch_user_*) +func (j *JobsGorm) PSubscribe(ctx context.Context) SubscribeResult { + return SubscribeResult{ + Message: j.redisClient.PSubscribe(ctx, j.config.cornKeyPrefix+"_"+j.config.cornKeyCustom+"_*"), + } +} diff --git a/utils/gojobs/jobs_gorm_redis_get.go b/utils/gojobs/jobs_gorm_redis_get.go new file mode 100644 index 00000000..2e6ee418 --- /dev/null +++ b/utils/gojobs/jobs_gorm_redis_get.go @@ -0,0 +1,96 @@ +package gojobs + +import ( + "context" + "errors" + "fmt" + "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" + "github.com/dtapps/go-library/utils/gostring" + "log" + "math/rand" + "time" +) + +// GetIssueAddress 获取下发地址 +// workers 在线列表 +// v 任务信息 +// --- +// address 下发地址 +// err 错误信息 +func (j *JobsGorm) GetIssueAddress(workers []string, v *jobs_gorm_model.Task) (address string, err error) { + var ( + currentIp = "" // 当前Ip + appointIpStatus = false // 指定Ip状态 + ) + + // 赋值ip + if v.SpecifyIp != "" { + currentIp = v.SpecifyIp + appointIpStatus = true + } + + // 只有一个客户端在线 + if len(workers) == 1 { + if appointIpStatus == true { + // 判断是否指定某ip执行 + if gostring.Contains(workers[0], currentIp) == true { + return j.config.cornKeyPrefix + "_" + v.SpecifyIp, nil + } + return address, errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp)) + } + return j.config.cornKeyPrefix + "_" + workers[0], nil + } + + // 优先处理指定某ip执行 + if appointIpStatus == true { + for wk, wv := range workers { + if gostring.Contains(wv, currentIp) == true { + return j.config.cornKeyPrefix + "_" + workers[wk], nil + } + } + return address, errors.New(fmt.Sprintf("需要执行的[%s]客户端不在线", currentIp)) + } else { + // 随机返回一个 + zxIp := workers[j.random(0, len(workers))] + if zxIp == "" { + return address, errors.New("获取执行的客户端异常") + } + address = j.config.cornKeyPrefix + "_" + zxIp + return address, err + } +} + +// GetSubscribeClientList 获取在线的客户端 +func (j *JobsGorm) GetSubscribeClientList(ctx context.Context) ([]string, error) { + + if j.config.debug == true { + log.Printf("获取在线的客户端:%s\n", j.config.cornKeyPrefix+"_*") + } + + // 扫描 + values, err := j.redisClient.Keys(ctx, j.config.cornKeyPrefix+"_*").Result() + if err != nil { + if err == errors.New("ERR wrong number of arguments for 'mget' command") { + return []string{}, nil + } + return nil, errors.New(fmt.Sprintf("获取失败:%s", err.Error())) + } + + client := make([]string, 0, len(values)) + for _, val := range values { + client = append(client, val.(string)) + } + + return client, nil +} + +// 随机返回一个 +// min最小 +// max最大 +func (j *JobsGorm) random(min, max int) int { + if max-min <= 0 { + return 0 + } + rand.Seed(time.Now().Unix()) + return rand.Intn(max-min) + min +} diff --git a/utils/gojobs/jobs_gorm_redis_ping.go b/utils/gojobs/jobs_gorm_redis_ping.go new file mode 100644 index 00000000..486b3561 --- /dev/null +++ b/utils/gojobs/jobs_gorm_redis_ping.go @@ -0,0 +1,22 @@ +package gojobs + +import ( + "context" + "github.com/robfig/cron/v3" + "log" + "time" +) + +// Ping 心跳 +func (j *JobsGorm) Ping(ctx context.Context) { + c := cron.New(cron.WithSeconds()) + _, _ = c.AddFunc(GetSeconds(2).Spec(), func() { + result, err := j.redisClient.Set(ctx, j.config.cornKeyPrefix+"_"+j.config.cornKeyCustom, j.config.cornKeyCustom, 3*time.Second).Result() + if j.config.debug == true { + log.Println("JOBS心跳", j.config.cornKeyPrefix+"_"+j.config.cornKeyCustom, j.config.cornKeyCustom, result, err) + } + }) + c.Start() + defer c.Stop() + select {} +} diff --git a/utils/gojobs/jobs_gorm_run.go b/utils/gojobs/jobs_gorm_run.go index 55ae64e3..089e1861 100644 --- a/utils/gojobs/jobs_gorm_run.go +++ b/utils/gojobs/jobs_gorm_run.go @@ -4,7 +4,7 @@ import ( "errors" "fmt" "github.com/dtapps/go-library/utils/gojobs/jobs_gorm_model" - "github.com/dtapps/go-library/utils/only" + "github.com/dtapps/go-library/utils/gostring" "gorm.io/gorm" "log" ) @@ -12,7 +12,7 @@ import ( // Run 运行 func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { // 请求函数记录 - err := j.service.gormClient.Create(&jobs_gorm_model.TaskLog{ + err := j.gormClient.Db.Create(&jobs_gorm_model.TaskLog{ TaskId: info.Id, StatusCode: status, Desc: desc, @@ -22,10 +22,10 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { log.Println("statusCreate", err.Error()) } if status == 0 { - err = j.EditTask(j.service.gormClient, info.Id). + err = j.EditTask(j.gormClient.Db, info.Id). Select("run_id"). Updates(jobs_gorm_model.Task{ - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), }).Error if err != nil { log.Println("statusEdit", err.Error()) @@ -35,12 +35,12 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { // 任务 if status == CodeSuccess { // 执行成功 - err = j.EditTask(j.service.gormClient, info.Id). + err = j.EditTask(j.gormClient.Db, info.Id). Select("status_desc", "number", "run_id", "updated_ip", "result"). Updates(jobs_gorm_model.Task{ StatusDesc: "执行成功", Number: info.Number + 1, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), UpdatedIp: j.config.outsideIp, Result: desc, }).Error @@ -50,7 +50,7 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { } if status == CodeEnd { // 执行成功、提前结束 - err = j.EditTask(j.service.gormClient, info.Id). + err = j.EditTask(j.gormClient.Db, info.Id). Select("status", "status_desc", "number", "updated_ip", "result"). Updates(jobs_gorm_model.Task{ Status: TASK_SUCCESS, @@ -65,12 +65,12 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { } if status == CodeError { // 执行失败 - err = j.EditTask(j.service.gormClient, info.Id). + err = j.EditTask(j.gormClient.Db, info.Id). Select("status_desc", "number", "run_id", "updated_ip", "result"). Updates(jobs_gorm_model.Task{ StatusDesc: "执行失败", Number: info.Number + 1, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), UpdatedIp: j.config.outsideIp, Result: desc, }).Error @@ -81,7 +81,7 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { if info.MaxNumber != 0 { if info.Number+1 >= info.MaxNumber { // 关闭执行 - err = j.EditTask(j.service.gormClient, info.Id). + err = j.EditTask(j.gormClient.Db, info.Id). Select("status"). Updates(jobs_gorm_model.Task{ Status: TASK_TIMEOUT, @@ -95,7 +95,7 @@ func (j *JobsGorm) Run(info jobs_gorm_model.Task, status int, desc string) { // RunAddLog 任务执行日志 func (j *JobsGorm) RunAddLog(id uint, runId string) error { - return j.service.gormClient.Create(&jobs_gorm_model.TaskLogRun{ + return j.gormClient.Db.Create(&jobs_gorm_model.TaskLogRun{ TaskId: id, RunId: runId, InsideIp: j.config.insideIp, @@ -116,6 +116,7 @@ type ConfigCreateInCustomId struct { CustomId string // 自定义编号 CustomSequence int64 // 自定义顺序 Type string // 类型 + TypeName string // 类型名称 SpecifyIp string // 指定外网IP CurrentIp string // 当前ip } @@ -130,10 +131,11 @@ func (j *JobsGorm) CreateInCustomId(config *ConfigCreateInCustomId) error { Params: config.Params, StatusDesc: "首次添加任务", Frequency: config.Frequency, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), CustomId: config.CustomId, CustomSequence: config.CustomSequence, Type: config.Type, + TypeName: config.TypeName, CreatedIp: config.CurrentIp, SpecifyIp: config.SpecifyIp, UpdatedIp: config.CurrentIp, @@ -152,6 +154,7 @@ type ConfigCreateInCustomIdOnly struct { CustomId string // 自定义编号 CustomSequence int64 // 自定义顺序 Type string // 类型 + TypeName string // 类型名称 SpecifyIp string // 指定外网IP CurrentIp string // 当前ip } @@ -170,10 +173,11 @@ func (j *JobsGorm) CreateInCustomIdOnly(config *ConfigCreateInCustomIdOnly) erro Params: config.Params, StatusDesc: "首次添加任务", Frequency: config.Frequency, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), CustomId: config.CustomId, CustomSequence: config.CustomSequence, Type: config.Type, + TypeName: config.TypeName, CreatedIp: config.CurrentIp, SpecifyIp: config.SpecifyIp, UpdatedIp: config.CurrentIp, @@ -193,6 +197,7 @@ type ConfigCreateInCustomIdMaxNumber struct { CustomId string // 自定义编号 CustomSequence int64 // 自定义顺序 Type string // 类型 + TypeName string // 类型名称 SpecifyIp string // 指定外网IP CurrentIp string // 当前ip } @@ -208,10 +213,11 @@ func (j *JobsGorm) CreateInCustomIdMaxNumber(config *ConfigCreateInCustomIdMaxNu StatusDesc: "首次添加任务", Frequency: config.Frequency, MaxNumber: config.MaxNumber, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), CustomId: config.CustomId, CustomSequence: config.CustomSequence, Type: config.Type, + TypeName: config.TypeName, CreatedIp: config.CurrentIp, SpecifyIp: config.SpecifyIp, UpdatedIp: config.CurrentIp, @@ -231,6 +237,7 @@ type ConfigCreateInCustomIdMaxNumberOnly struct { CustomId string // 自定义编号 CustomSequence int64 // 自定义顺序 Type string // 类型 + TypeName string // 类型名称 SpecifyIp string // 指定外网IP CurrentIp string // 当前ip } @@ -250,10 +257,11 @@ func (j *JobsGorm) CreateInCustomIdMaxNumberOnly(config *ConfigCreateInCustomIdM StatusDesc: "首次添加任务", Frequency: config.Frequency, MaxNumber: config.MaxNumber, - RunId: only.GetUuId(), + RunId: gostring.GetUuId(), CustomId: config.CustomId, CustomSequence: config.CustomSequence, Type: config.Type, + TypeName: config.TypeName, CreatedIp: config.CurrentIp, SpecifyIp: config.SpecifyIp, UpdatedIp: config.CurrentIp, diff --git a/utils/gojobs/jobs_zorm.go b/utils/gojobs/jobs_zorm.go deleted file mode 100644 index a38e58ab..00000000 --- a/utils/gojobs/jobs_zorm.go +++ /dev/null @@ -1,21 +0,0 @@ -package gojobs - -import "gitee.com/chunanyong/zorm" - -// Zorm数据库驱动 -type jobsZorm struct { - db *zorm.DBDao -} - -// NewJobsZorm 初始化 -func NewJobsZorm(db *zorm.DBDao) *jobsZorm { - var ( - j = &jobsZorm{} - ) - j.db = db - return j -} - -func (j *jobsZorm) Run() { - -} diff --git a/utils/gojobs/jobs_zorm_model/task.go b/utils/gojobs/jobs_zorm_model/task.go deleted file mode 100644 index baf194c5..00000000 --- a/utils/gojobs/jobs_zorm_model/task.go +++ /dev/null @@ -1,28 +0,0 @@ -package jobs_zorm_model - -// Task 任务 -type Task struct { - Id uint `zorm:"primaryKey" json:"id"` // 记录编号 - Status string `json:"status"` // 状态码 - Params string `json:"params"` // 参数 - ParamsType string `json:"params_type"` // 参数类型 - StatusDesc string `json:"status_desc"` // 状态描述 - Frequency int64 `json:"frequency"` // 频率(秒单位) - Number int64 `json:"number"` // 当前次数 - MaxNumber int64 `json:"max_number"` // 最大次数 - RunId string `json:"run_id"` // 执行编号 - CustomId string `json:"custom_id"` // 自定义编号 - CustomSequence int64 `json:"custom_sequence"` // 自定义顺序 - Type string `json:"type"` // 类型 - CreatedIp string `json:"created_ip"` // 创建外网IP - SpecifyIp string `json:"specify_ip"` // 指定外网IP - UpdatedIp string `json:"updated_ip"` // 更新外网IP - Result string `json:"result"` // 结果 - CreatedAt string `zorm:"type:text" json:"created_at"` // 创建时间 - UpdatedAt string `zorm:"type:text" json:"updated_at"` // 更新时间 - DeletedAt string `zorm:"index;deleted" json:"deleted_at"` // 删除时间 -} - -func (m *Task) TableName() string { - return "task" -} diff --git a/utils/gojobs/jobs_zorm_model/task_ip.go b/utils/gojobs/jobs_zorm_model/task_ip.go deleted file mode 100644 index 8256304c..00000000 --- a/utils/gojobs/jobs_zorm_model/task_ip.go +++ /dev/null @@ -1,12 +0,0 @@ -package jobs_zorm_model - -// TaskIp 任务Ip -type TaskIp struct { - Id int64 `zorm:"primaryKey" json:"id"` - TaskType string `json:"task_type"` // 任务编号 - Ips string `json:"ips"` // 任务IP -} - -func (m *TaskIp) TableName() string { - return "task_ip" -} diff --git a/utils/gojobs/jobs_zorm_model/task_log.go b/utils/gojobs/jobs_zorm_model/task_log.go deleted file mode 100644 index d9b12f57..00000000 --- a/utils/gojobs/jobs_zorm_model/task_log.go +++ /dev/null @@ -1,15 +0,0 @@ -package jobs_zorm_model - -// TaskLog 任务日志模型 -type TaskLog struct { - Id uint `zorm:"primaryKey" json:"id"` // 记录编号 - TaskId uint `json:"task_id"` // 任务编号 - StatusCode int `json:"status_code"` // 状态码 - Desc string `json:"desc"` // 结果 - Version int `json:"version"` // 版本 - CreatedAt string `zorm:"type:text" json:"created_at"` // 创建时间 -} - -func (m *TaskLog) TableName() string { - return "task_log" -} diff --git a/utils/gojobs/jobs_zorm_model/task_log_run.go b/utils/gojobs/jobs_zorm_model/task_log_run.go deleted file mode 100644 index bdfad445..00000000 --- a/utils/gojobs/jobs_zorm_model/task_log_run.go +++ /dev/null @@ -1,20 +0,0 @@ -package jobs_zorm_model - -// TaskLogRun 任务执行日志模型 -type TaskLogRun struct { - Id uint `zorm:"primaryKey" json:"id"` // 记录编号 - TaskId uint `json:"task_id"` // 任务编号 - RunId string `json:"run_id"` // 执行编号 - OutsideIp string `json:"outside_ip"` // 外网ip - InsideIp string `json:"inside_ip"` // 内网ip - Os string `json:"os"` // 系统类型 - Arch string `json:"arch"` // 系统架构 - Gomaxprocs int `json:"gomaxprocs"` // CPU核数 - GoVersion string `json:"go_version"` // GO版本 - MacAddrs string `json:"mac_addrs"` // Mac地址 - CreatedAt string `zorm:"type:text" json:"created_at"` // 创建时间 -} - -func (m *TaskLogRun) TableName() string { - return "task_log_run" -} diff --git a/utils/gojobs/operation_attr.go b/utils/gojobs/operation_attr.go deleted file mode 100644 index 4685eacb..00000000 --- a/utils/gojobs/operation_attr.go +++ /dev/null @@ -1,56 +0,0 @@ -package gojobs - -import ( - "github.com/dtapps/go-library/utils/goip" - "github.com/go-redis/redis/v8" - "go.etcd.io/etcd/client/v3" - "gorm.io/gorm" -) - -const ( - lockTypeRedis = "redis" - lockTypeEtcd = "etcd" -) - -// OperationAttr 操作属性 -type OperationAttr struct { - gormClient *gorm.DB // 数据库驱动 - redisClient *redis.Client // 缓存数据库驱动 - etcdClient *clientv3.Client // 分布式缓存驱动 - lockPrefix string // 锁Key前缀 - ipService *goip.Client // ip服务 - lockType string // 锁驱动类型 - outsideIp string // 外网ip -} - -// WithGormClient 设置数据库驱动 -func WithGormClient(client *gorm.DB) *OperationAttr { - return &OperationAttr{gormClient: client} -} - -// WithRedisClient 设置缓存数据库驱动 -func WithRedisClient(redisClient *redis.Client) *OperationAttr { - return &OperationAttr{redisClient: redisClient, lockType: lockTypeRedis} -} - -// WithEtcdClient 设置分布式缓存驱动 -func WithEtcdClient(etcdClient *clientv3.Client) *OperationAttr { - return &OperationAttr{etcdClient: etcdClient, lockType: lockTypeEtcd} -} - -// WithLockPrefix 设置锁Key前缀 -// redis:fmt.Sprintf("cron:lock:%v:%v", info.Type, id) -// etcd:fmt.Sprintf("cron/lock/%v/%v", info.Type, id) -func WithLockPrefix(lockPrefix string) *OperationAttr { - return &OperationAttr{lockPrefix: lockPrefix} -} - -// WithOutsideIp 设置外网ip -func WithOutsideIp(outsideIp string) *OperationAttr { - return &OperationAttr{outsideIp: outsideIp} -} - -// WithIpService 设置ip服务 -func WithIpService(ipService *goip.Client) *OperationAttr { - return &OperationAttr{ipService: ipService} -} diff --git a/utils/golock/etcd.go b/utils/golock/etcd.go deleted file mode 100644 index 2e0f7cff..00000000 --- a/utils/golock/etcd.go +++ /dev/null @@ -1,76 +0,0 @@ -package golock - -import ( - "context" - "errors" - "fmt" - "go.etcd.io/etcd/client/v3" -) - -type LockEtcd struct { - etcdClient *clientv3.Client // 驱动 -} - -func NewLockEtcd(etcdClient *clientv3.Client) *LockEtcd { - return &LockEtcd{etcdClient: etcdClient} -} - -// Lock 上锁 -// key 锁名 -// val 锁内容 -// ttl 锁过期时间 -func (e *LockEtcd) Lock(key string, val string, ttl int64) (string, error) { - if ttl <= 0 { - return "", errors.New("长期请使用 LockForever 方法") - } - // 1、获取 - get, err := e.etcdClient.Get(context.Background(), key) - if err != nil { - return "", errors.New("获取异常") - } - if len(get.Kvs) > 0 { - return "", errors.New("上锁失败,已存在") - } - // 2、申请一个lease(租约) - lease := clientv3.NewLease(e.etcdClient) - // 3、申请一个*秒的租约 - leaseGrantResp, err := lease.Grant(context.TODO(), ttl) - if err != nil { - return "", errors.New(fmt.Sprintf("申请租约失败 %s", err)) - } - // 5、获得kv api子集 - kv := clientv3.NewKV(e.etcdClient) - // 4、设置 - kv.Put(context.TODO(), key, val, clientv3.WithLease(leaseGrantResp.ID)) - if err != nil { - return "", errors.New("上锁失败") - } - return val, nil -} - -// Unlock 解锁 -// key 锁名 -func (e *LockEtcd) Unlock(key string) error { - _, err := e.etcdClient.Delete(context.Background(), key) - return err -} - -// LockForever 永远上锁 -// key 锁名 -// val 锁内容 -func (e *LockEtcd) LockForever(key string, val string) (string, error) { - // 1、获取 - get, err := e.etcdClient.Get(context.Background(), key) - if err != nil { - return "", errors.New("获取异常") - } - if len(get.Kvs) > 0 { - return "", errors.New("上锁失败,已存在") - } - // 2、设置 - e.etcdClient.Put(context.TODO(), key, val) - if err != nil { - return "", errors.New("上锁失败") - } - return val, nil -} diff --git a/utils/golock/redis.go b/utils/golock/redis.go index d082511a..4f6acfb3 100644 --- a/utils/golock/redis.go +++ b/utils/golock/redis.go @@ -3,38 +3,38 @@ package golock import ( "context" "errors" - "github.com/go-redis/redis/v8" + "github.com/dtapps/go-library/utils/dorm" "time" ) type LockRedis struct { - redisClient *redis.Client // 驱动 + client *dorm.RedisClient // 驱动 } -func NewLockRedis(redisClient *redis.Client) *LockRedis { - return &LockRedis{redisClient: redisClient} +func NewLockRedis(client *dorm.RedisClient) *LockRedis { + return &LockRedis{client: client} } // Lock 上锁 // key 锁名 // val 锁内容 // ttl 锁过期时间 -func (r *LockRedis) Lock(key string, val string, ttl int64) (string, error) { +func (r *LockRedis) Lock(key string, val string, ttl time.Duration) (resp string, err error) { if ttl <= 0 { - return "", errors.New("长期请使用 LockForever 方法") + return resp, errors.New("长期请使用 LockForever 方法") } - // 1、获取 - get, err := r.redisClient.Get(context.Background(), key).Result() + // 获取 + get, err := r.client.Get(context.Background(), key).Result() if err != nil { - return "", errors.New("获取异常") + return resp, errors.New("获取异常") } if get != "" { - return "", errors.New("上锁失败,已存在") + return resp, errors.New("上锁失败,已存在") } - // 2、设置 - err = r.redisClient.Set(context.Background(), key, val, time.Duration(ttl)).Err() + // 设置 + err = r.client.Set(context.Background(), key, val, ttl).Err() if err != nil { - return "", errors.New("上锁失败") + return resp, errors.New("上锁失败") } return val, nil } @@ -42,26 +42,26 @@ func (r *LockRedis) Lock(key string, val string, ttl int64) (string, error) { // Unlock 解锁 // key 锁名 func (r *LockRedis) Unlock(key string) error { - _, err := r.redisClient.Del(context.Background(), key).Result() + _, err := r.client.Del(context.Background(), key).Result() return err } // LockForever 永远上锁 // key 锁名 // val 锁内容 -func (r *LockRedis) LockForever(key string, val string) (string, error) { - // 1、获取 - get, err := r.redisClient.Get(context.Background(), key).Result() +func (r *LockRedis) LockForever(key string, val string) (resp string, err error) { + // 获取 + get, err := r.client.Get(context.Background(), key).Result() if err != nil { - return "", errors.New("获取异常") + return resp, errors.New("获取异常") } if get != "" { - return "", errors.New("上锁失败,已存在") + return resp, errors.New("上锁失败,已存在") } - // 2、设置 - err = r.redisClient.Set(context.Background(), key, val, 0).Err() + // 设置 + err = r.client.Set(context.Background(), key, val, 0).Err() if err != nil { - return "", errors.New("上锁失败") + return resp, errors.New("上锁失败") } return val, nil } diff --git a/utils/golock/zookeeper.go b/utils/golock/zookeeper.go deleted file mode 100644 index 6defed67..00000000 --- a/utils/golock/zookeeper.go +++ /dev/null @@ -1 +0,0 @@ -package golock diff --git a/utils/golog/api.go b/utils/golog/api.go index a45d6e44..d0716919 100644 --- a/utils/golog/api.go +++ b/utils/golog/api.go @@ -1,6 +1,7 @@ package golog import ( + "context" "errors" "github.com/dtapps/go-library/utils/dorm" "github.com/dtapps/go-library/utils/goip" @@ -87,7 +88,7 @@ func NewApiClient(attrs ...*OperationAttr) (*ApiClient, error) { hostname, _ := os.Hostname() c.config.hostname = hostname - c.config.insideIp = goip.GetInsideIp() + c.config.insideIp = goip.GetInsideIp(context.Background()) c.config.goVersion = runtime.Version() return c, nil diff --git a/utils/golog/api_gorm.go b/utils/golog/api_gorm.go index 348727f7..4483c7aa 100644 --- a/utils/golog/api_gorm.go +++ b/utils/golog/api_gorm.go @@ -1,9 +1,12 @@ package golog import ( + "context" "github.com/dtapps/go-library/utils/dorm" "github.com/dtapps/go-library/utils/gojson" "github.com/dtapps/go-library/utils/gorequest" + "github.com/dtapps/go-library/utils/gotrace_id" + "github.com/dtapps/go-library/utils/gourl" "gorm.io/datatypes" "gorm.io/gorm" "log" @@ -13,29 +16,30 @@ import ( // 模型结构体 type apiPostgresqlLog struct { - LogId uint `gorm:"primaryKey" json:"log_id,omitempty"` //【记录】编号 - RequestTime time.Time `gorm:"index" json:"request_time,omitempty"` //【请求】时间 - RequestUri string `json:"request_uri,omitempty"` //【请求】链接 - RequestUrl string `json:"request_url,omitempty"` //【请求】链接 - RequestApi string `gorm:"index" json:"request_api,omitempty"` //【请求】接口 - RequestMethod string `gorm:"index" json:"request_method,omitempty"` //【请求】方式 - RequestParams datatypes.JSON `gorm:"type:jsonb" json:"request_params,omitempty"` //【请求】参数 - RequestHeader datatypes.JSON `gorm:"type:jsonb" json:"request_header,omitempty"` //【请求】头部 - ResponseHeader datatypes.JSON `gorm:"type:jsonb" json:"response_header,omitempty"` //【返回】头部 - ResponseStatusCode int `gorm:"index" json:"response_status_code,omitempty"` //【返回】状态码 - ResponseBody datatypes.JSON `gorm:"type:jsonb" json:"response_body,omitempty"` //【返回】内容 - ResponseContentLength int64 `json:"response_content_length,omitempty"` //【返回】大小 - ResponseTime time.Time `gorm:"index" json:"response_time,omitempty"` //【返回】时间 - SystemHostName string `gorm:"index" json:"system_host_name,omitempty"` //【系统】主机名 - SystemInsideIp string `gorm:"index" json:"system_inside_ip,omitempty"` //【系统】内网ip - GoVersion string `gorm:"index" json:"go_version,omitempty"` //【程序】Go版本 + LogId uint `gorm:"primaryKey;comment:【记录】编号" json:"log_id,omitempty"` //【记录】编号 + TraceId string `gorm:"index;comment:【系统】跟踪编号" json:"trace_id,omitempty"` //【系统】跟踪编号 + RequestTime time.Time `gorm:"index;comment:【请求】时间" json:"request_time,omitempty"` //【请求】时间 + RequestUri string `gorm:"comment:【请求】链接" json:"request_uri,omitempty"` //【请求】链接 + RequestUrl string `gorm:"comment:【请求】链接" json:"request_url,omitempty"` //【请求】链接 + RequestApi string `gorm:"index;comment:【请求】接口" json:"request_api,omitempty"` //【请求】接口 + RequestMethod string `gorm:"index;comment:【请求】方式" json:"request_method,omitempty"` //【请求】方式 + RequestParams datatypes.JSON `gorm:"type:jsonb;comment:【请求】参数" json:"request_params,omitempty"` //【请求】参数 + RequestHeader datatypes.JSON `gorm:"type:jsonb;comment:【请求】头部" json:"request_header,omitempty"` //【请求】头部 + ResponseHeader datatypes.JSON `gorm:"type:jsonb;comment:【返回】头部" json:"response_header,omitempty"` //【返回】头部 + ResponseStatusCode int `gorm:"index;comment:【返回】状态码" json:"response_status_code,omitempty"` //【返回】状态码 + ResponseBody datatypes.JSON `gorm:"type:jsonb;comment:【返回】内容" json:"response_body,omitempty"` //【返回】内容 + ResponseContentLength int64 `gorm:"comment:【返回】大小" json:"response_content_length,omitempty"` //【返回】大小 + ResponseTime time.Time `gorm:"index;comment:【返回】时间" json:"response_time,omitempty"` //【返回】时间 + SystemHostName string `gorm:"index;comment:【系统】主机名" json:"system_host_name,omitempty"` //【系统】主机名 + SystemInsideIp string `gorm:"index;comment:【系统】内网ip" json:"system_inside_ip,omitempty"` //【系统】内网ip + GoVersion string `gorm:"index;comment:【程序】Go版本" json:"go_version,omitempty"` //【程序】Go版本 + SdkVersion string `gorm:"index;comment:【程序】Sdk版本" json:"sdk_version,omitempty"` //【程序】Sdk版本 } // 记录日志 -func (c *ApiClient) gormRecord(postgresqlLog apiPostgresqlLog) error { +func (c *ApiClient) gormRecord(ctx context.Context, postgresqlLog apiPostgresqlLog) error { if utf8.ValidString(string(postgresqlLog.ResponseBody)) == false { - log.Println("内容格式无法记录") postgresqlLog.ResponseBody = datatypes.JSON("") } @@ -45,6 +49,8 @@ func (c *ApiClient) gormRecord(postgresqlLog apiPostgresqlLog) error { } postgresqlLog.GoVersion = c.config.goVersion + postgresqlLog.TraceId = gotrace_id.GetTraceIdContext(ctx) + return c.gormClient.Table(c.config.tableName).Create(&postgresqlLog).Error } @@ -54,16 +60,15 @@ func (c *ApiClient) GormQuery() *gorm.DB { } // GormMiddleware 中间件 -func (c *ApiClient) GormMiddleware(request gorequest.Response) { +func (c *ApiClient) GormMiddleware(ctx context.Context, request gorequest.Response, sdkVersion string) { if request.ResponseHeader.Get("Content-Type") == "image/jpeg" || request.ResponseHeader.Get("Content-Type") == "image/png" { - log.Println("内容格式无法记录") return } - c.gormRecord(apiPostgresqlLog{ + err := c.gormRecord(ctx, apiPostgresqlLog{ RequestTime: request.RequestTime, //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 - RequestApi: gorequest.UriParse(request.RequestUri).Path, //【请求】接口 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 + RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: datatypes.JSON(gojson.JsonEncodeNoError(request.RequestParams)), //【请求】参数 RequestHeader: datatypes.JSON(gojson.JsonEncodeNoError(request.RequestHeader)), //【请求】头部 @@ -72,16 +77,20 @@ func (c *ApiClient) GormMiddleware(request gorequest.Response) { ResponseBody: request.ResponseBody, //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: request.ResponseTime, //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) + if err != nil { + log.Println("log.GormMiddleware:", err.Error()) + } } // GormMiddlewareXml 中间件 -func (c *ApiClient) GormMiddlewareXml(request gorequest.Response) { - c.gormRecord(apiPostgresqlLog{ +func (c *ApiClient) GormMiddlewareXml(ctx context.Context, request gorequest.Response, sdkVersion string) { + err := c.gormRecord(ctx, apiPostgresqlLog{ RequestTime: request.RequestTime, //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 - RequestApi: gorequest.UriParse(request.RequestUri).Path, //【请求】接口 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 + RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: datatypes.JSON(gojson.JsonEncodeNoError(request.RequestParams)), //【请求】参数 RequestHeader: datatypes.JSON(gojson.JsonEncodeNoError(request.RequestHeader)), //【请求】头部 @@ -90,15 +99,19 @@ func (c *ApiClient) GormMiddlewareXml(request gorequest.Response) { ResponseBody: datatypes.JSON(gojson.JsonEncodeNoError(dorm.XmlDecodeNoError(request.ResponseBody))), //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: request.ResponseTime, //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) + if err != nil { + log.Println("log.GormMiddlewareXml:", err.Error()) + } } // GormMiddlewareCustom 中间件 -func (c *ApiClient) GormMiddlewareCustom(api string, request gorequest.Response) { - c.gormRecord(apiPostgresqlLog{ +func (c *ApiClient) GormMiddlewareCustom(ctx context.Context, api string, request gorequest.Response, sdkVersion string) { + err := c.gormRecord(ctx, apiPostgresqlLog{ RequestTime: request.RequestTime, //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 RequestApi: api, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: datatypes.JSON(gojson.JsonEncodeNoError(request.RequestParams)), //【请求】参数 @@ -108,5 +121,9 @@ func (c *ApiClient) GormMiddlewareCustom(api string, request gorequest.Response) ResponseBody: request.ResponseBody, //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: request.ResponseTime, //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) + if err != nil { + log.Println("log.GormMiddlewareCustom:", err.Error()) + } } diff --git a/utils/golog/api_mongo.go b/utils/golog/api_mongo.go index ccc75789..ff096244 100644 --- a/utils/golog/api_mongo.go +++ b/utils/golog/api_mongo.go @@ -1,15 +1,19 @@ package golog import ( + "context" "github.com/dtapps/go-library/utils/dorm" "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gotime" + "github.com/dtapps/go-library/utils/gotrace_id" + "github.com/dtapps/go-library/utils/gourl" "go.mongodb.org/mongo-driver/bson/primitive" ) // 模型结构体 type apiMongoLog struct { LogId primitive.ObjectID `json:"log_id,omitempty" bson:"_id,omitempty"` //【记录】编号 + TraceId string `json:"trace_id,omitempty" bson:"trace_id,omitempty"` //【系统】跟踪编号 RequestTime int64 `json:"request_time,omitempty" bson:"request_time,omitempty"` //【请求】时间 RequestUri string `json:"request_uri,omitempty" bson:"request_uri,omitempty"` //【请求】链接 RequestUrl string `json:"request_url,omitempty" bson:"request_url,omitempty"` //【请求】链接 @@ -25,10 +29,11 @@ type apiMongoLog struct { SystemHostName string `json:"system_host_name,omitempty" bson:"system_host_name,omitempty"` //【系统】主机名 SystemInsideIp string `json:"system_inside_ip,omitempty" bson:"system_inside_ip,omitempty"` //【系统】内网ip GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【程序】Go版本 + SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【程序】Sdk版本 } // 记录日志 -func (c *ApiClient) mongoRecord(mongoLog apiMongoLog) error { +func (c *ApiClient) mongoRecord(ctx context.Context, mongoLog apiMongoLog) error { mongoLog.SystemHostName = c.config.hostname if mongoLog.SystemInsideIp == "" { @@ -36,6 +41,8 @@ func (c *ApiClient) mongoRecord(mongoLog apiMongoLog) error { } mongoLog.GoVersion = c.config.goVersion + mongoLog.TraceId = gotrace_id.GetTraceIdContext(ctx) + mongoLog.LogId = primitive.NewObjectID() _, err := c.mongoClient.Database(c.config.databaseName).Collection(c.config.collectionName).InsertOne(mongoLog) @@ -49,12 +56,12 @@ func (c *ApiClient) MongoQuery() *dorm.MongoClient { } // MongoMiddleware 中间件 -func (c *ApiClient) MongoMiddleware(request gorequest.Response) { - c.mongoRecord(apiMongoLog{ +func (c *ApiClient) MongoMiddleware(ctx context.Context, request gorequest.Response, sdkVersion string) { + c.mongoRecord(ctx, apiMongoLog{ RequestTime: gotime.SetCurrent(request.RequestTime).Timestamp(), //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 - RequestApi: gorequest.UriParse(request.RequestUri).Path, //【请求】接口 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 + RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: request.RequestParams, //【请求】参数 RequestHeader: request.RequestHeader, //【请求】头部 @@ -63,16 +70,17 @@ func (c *ApiClient) MongoMiddleware(request gorequest.Response) { ResponseBody: request.ResponseBody, //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: gotime.SetCurrent(request.ResponseTime).Timestamp(), //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) } // MongoMiddlewareXml 中间件 -func (c *ApiClient) MongoMiddlewareXml(request gorequest.Response) { - c.mongoRecord(apiMongoLog{ +func (c *ApiClient) MongoMiddlewareXml(ctx context.Context, request gorequest.Response, sdkVersion string) { + c.mongoRecord(ctx, apiMongoLog{ RequestTime: gotime.SetCurrent(request.RequestTime).Timestamp(), //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 - RequestApi: gorequest.UriParse(request.RequestUri).Path, //【请求】接口 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 + RequestApi: gourl.UriParse(request.RequestUri).Path, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: request.RequestParams, //【请求】参数 RequestHeader: request.RequestHeader, //【请求】头部 @@ -81,15 +89,16 @@ func (c *ApiClient) MongoMiddlewareXml(request gorequest.Response) { ResponseBody: dorm.XmlDecodeNoError(request.ResponseBody), //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: gotime.SetCurrent(request.ResponseTime).Timestamp(), //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) } // MongoMiddlewareCustom 中间件 -func (c *ApiClient) MongoMiddlewareCustom(api string, request gorequest.Response) { - c.mongoRecord(apiMongoLog{ +func (c *ApiClient) MongoMiddlewareCustom(ctx context.Context, api string, request gorequest.Response, sdkVersion string) { + c.mongoRecord(ctx, apiMongoLog{ RequestTime: gotime.SetCurrent(request.RequestTime).Timestamp(), //【请求】时间 RequestUri: request.RequestUri, //【请求】链接 - RequestUrl: gorequest.UriParse(request.RequestUri).Url, //【请求】链接 + RequestUrl: gourl.UriParse(request.RequestUri).Url, //【请求】链接 RequestApi: api, //【请求】接口 RequestMethod: request.RequestMethod, //【请求】方式 RequestParams: request.RequestParams, //【请求】参数 @@ -99,5 +108,6 @@ func (c *ApiClient) MongoMiddlewareCustom(api string, request gorequest.Response ResponseBody: request.ResponseBody, //【返回】内容 ResponseContentLength: request.ResponseContentLength, //【返回】大小 ResponseTime: gotime.SetCurrent(request.ResponseTime).Timestamp(), //【返回】时间 + SdkVersion: sdkVersion, //【程序】Sdk版本 }) } diff --git a/utils/golog/gin.go b/utils/golog/gin.go index e1ac04ce..70c7b935 100644 --- a/utils/golog/gin.go +++ b/utils/golog/gin.go @@ -2,6 +2,7 @@ package golog import ( "bytes" + "context" "encoding/json" "errors" "github.com/dtapps/go-library/utils/dorm" @@ -94,7 +95,7 @@ func NewGinClient(attrs ...*OperationAttr) (*GinClient, error) { hostname, _ := os.Hostname() c.config.hostname = hostname - c.config.insideIp = goip.GetInsideIp() + c.config.insideIp = goip.GetInsideIp(context.Background()) c.config.goVersion = runtime.Version() return c, nil diff --git a/utils/golog/gin_gorm.go b/utils/golog/gin_gorm.go index aba3ac69..2d5139cf 100644 --- a/utils/golog/gin_gorm.go +++ b/utils/golog/gin_gorm.go @@ -4,46 +4,49 @@ import ( "bytes" "encoding/json" "github.com/dtapps/go-library/utils/gojson" - "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gotime" + "github.com/dtapps/go-library/utils/gotrace_id" + "github.com/dtapps/go-library/utils/gourl" "github.com/dtapps/go-library/utils/goxml" "github.com/gin-gonic/gin" "gorm.io/datatypes" "gorm.io/gorm" "io/ioutil" + "log" "net" "time" ) // 模型结构体 type ginPostgresqlLog struct { - LogId uint `gorm:"primaryKey" json:"log_id,omitempty"` //【记录】编号 - TraceId string `gorm:"index" json:"trace_id,omitempty"` //【系统】链编号 - RequestTime time.Time `gorm:"index" json:"request_time,omitempty"` //【请求】时间 - RequestUri string `json:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数 - RequestUrl string `json:"request_url,omitempty"` //【请求】请求链接 域名+路径 - RequestApi string `gorm:"index" json:"request_api,omitempty"` //【请求】请求接口 路径 - RequestMethod string `gorm:"index" json:"request_method,omitempty"` //【请求】请求方式 - RequestProto string `json:"request_proto,omitempty"` //【请求】请求协议 - RequestUa string `json:"request_ua,omitempty"` //【请求】请求UA - RequestReferer string `json:"request_referer,omitempty"` //【请求】请求referer - RequestBody datatypes.JSON `gorm:"type:jsonb" json:"request_body,omitempty"` //【请求】请求主体 - RequestUrlQuery datatypes.JSON `gorm:"type:jsonb" json:"request_url_query,omitempty"` //【请求】请求URL参数 - RequestIp string `gorm:"index" json:"request_ip,omitempty"` //【请求】请求客户端Ip - RequestIpCountry string `gorm:"index" json:"request_ip_country,omitempty"` //【请求】请求客户端城市 - RequestIpRegion string `gorm:"index" json:"request_ip_region,omitempty"` //【请求】请求客户端区域 - RequestIpProvince string `gorm:"index" json:"request_ip_province,omitempty"` //【请求】请求客户端省份 - RequestIpCity string `gorm:"index" json:"request_ip_city,omitempty"` //【请求】请求客户端城市 - RequestIpIsp string `gorm:"index" json:"request_ip_isp,omitempty"` //【请求】请求客户端运营商 - RequestHeader datatypes.JSON `gorm:"type:jsonb" json:"request_header,omitempty"` //【请求】请求头 - ResponseTime time.Time `gorm:"index" json:"response_time,omitempty"` //【返回】时间 - ResponseCode int `gorm:"index" json:"response_code,omitempty"` //【返回】状态码 - ResponseMsg string `json:"response_msg,omitempty"` //【返回】描述 - ResponseData datatypes.JSON `gorm:"type:jsonb" json:"response_data,omitempty"` //【返回】数据 - CostTime int64 `json:"cost_time,omitempty"` //【系统】花费时间 - SystemHostName string `gorm:"index" json:"system_host_name,omitempty"` //【系统】主机名 - SystemInsideIp string `gorm:"index" json:"system_inside_ip,omitempty"` //【系统】内网ip - GoVersion string `gorm:"index" json:"go_version,omitempty"` //【程序】Go版本 + LogId uint `gorm:"primaryKey;comment:【记录】编号" json:"log_id,omitempty"` //【记录】编号 + TraceId string `gorm:"index;comment:【系统】跟踪编号" json:"trace_id,omitempty"` //【系统】跟踪编号 + RequestTime time.Time `gorm:"index;comment:【请求】时间" json:"request_time,omitempty"` //【请求】时间 + RequestUri string `gorm:"comment:【请求】请求链接 域名+路径+参数" json:"request_uri,omitempty"` //【请求】请求链接 域名+路径+参数 + RequestUrl string `gorm:"comment:【请求】请求链接 域名+路径" json:"request_url,omitempty"` //【请求】请求链接 域名+路径 + RequestApi string `gorm:"index;comment:【请求】请求接口 路径" json:"request_api,omitempty"` //【请求】请求接口 路径 + RequestMethod string `gorm:"index;comment:【请求】请求方式" json:"request_method,omitempty"` //【请求】请求方式 + RequestProto string `gorm:"comment:【请求】请求协议" json:"request_proto,omitempty"` //【请求】请求协议 + RequestUa string `gorm:"comment:【请求】请求UA" json:"request_ua,omitempty"` //【请求】请求UA + RequestReferer string `gorm:"comment:【请求】请求referer" json:"request_referer,omitempty"` //【请求】请求referer + RequestBody datatypes.JSON `gorm:"type:jsonb;comment:【请求】请求主体" json:"request_body,omitempty"` //【请求】请求主体 + RequestUrlQuery datatypes.JSON `gorm:"type:jsonb;comment:【请求】请求URL参数" json:"request_url_query,omitempty"` //【请求】请求URL参数 + RequestIp string `gorm:"index;comment:【请求】请求客户端Ip" json:"request_ip,omitempty"` //【请求】请求客户端Ip + RequestIpCountry string `gorm:"index;comment:【请求】请求客户端城市" json:"request_ip_country,omitempty"` //【请求】请求客户端城市 + RequestIpRegion string `gorm:"index;comment:【请求】请求客户端区域" json:"request_ip_region,omitempty"` //【请求】请求客户端区域 + RequestIpProvince string `gorm:"index;comment:【请求】请求客户端省份" json:"request_ip_province,omitempty"` //【请求】请求客户端省份 + RequestIpCity string `gorm:"index;comment:【请求】请求客户端城市" json:"request_ip_city,omitempty"` //【请求】请求客户端城市 + RequestIpIsp string `gorm:"index;comment:【请求】请求客户端运营商" json:"request_ip_isp,omitempty"` //【请求】请求客户端运营商 + RequestHeader datatypes.JSON `gorm:"type:jsonb;comment:【请求】请求头" json:"request_header,omitempty"` //【请求】请求头 + ResponseTime time.Time `gorm:"index;comment:【返回】时间" json:"response_time,omitempty"` //【返回】时间 + ResponseCode int `gorm:"index;comment:【返回】状态码" json:"response_code,omitempty"` //【返回】状态码 + ResponseMsg string `gorm:"comment:【返回】描述" json:"response_msg,omitempty"` //【返回】描述 + ResponseData datatypes.JSON `gorm:"type:jsonb;comment:【返回】数据" json:"response_data,omitempty"` //【返回】数据 + CostTime int64 `gorm:"comment:【系统】花费时间" json:"cost_time,omitempty"` //【系统】花费时间 + SystemHostName string `gorm:"index;comment:【系统】主机名" json:"system_host_name,omitempty"` //【系统】主机名 + SystemInsideIp string `gorm:"index;comment:【系统】内网ip" json:"system_inside_ip,omitempty"` //【系统】内网ip + GoVersion string `gorm:"index;comment:【程序】Go版本" json:"go_version,omitempty"` //【程序】Go版本 + SdkVersion string `gorm:"index;comment:【程序】Sdk版本" json:"sdk_version,omitempty"` //【程序】Sdk版本 } // gormRecord 记录日志 @@ -55,6 +58,8 @@ func (c *GinClient) gormRecord(postgresqlLog ginPostgresqlLog) error { } postgresqlLog.GoVersion = c.config.goVersion + postgresqlLog.SdkVersion = Version + return c.gormClient.Table(c.config.tableName).Create(&postgresqlLog).Error } @@ -128,12 +133,12 @@ func (c *GinClient) GormMiddleware() gin.HandlerFunc { host = "https://" + ginCtx.Request.Host } if len(jsonBody) > 0 { - c.gormRecord(ginPostgresqlLog{ - TraceId: ginCtx.MustGet("trace_id").(string), //【系统】链编号 + err := c.gormRecord(ginPostgresqlLog{ + TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号 RequestTime: requestTime, //【请求】时间 RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 - RequestApi: gorequest.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 + RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 RequestMethod: ginCtx.Request.Method, //【请求】请求方式 RequestProto: ginCtx.Request.Proto, //【请求】请求协议 RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA @@ -152,13 +157,16 @@ func (c *GinClient) GormMiddleware() gin.HandlerFunc { ResponseData: datatypes.JSON(responseBody), //【返回】数据 CostTime: endTime - startTime, //【系统】花费时间 }) + if err != nil { + log.Println("log.gormRecord:", err.Error()) + } } else { - c.gormRecord(ginPostgresqlLog{ - TraceId: ginCtx.MustGet("trace_id").(string), //【系统】链编号 + err := c.gormRecord(ginPostgresqlLog{ + TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号 RequestTime: requestTime, //【请求】时间 RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 - RequestApi: gorequest.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 + RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 RequestMethod: ginCtx.Request.Method, //【请求】请求方式 RequestProto: ginCtx.Request.Proto, //【请求】请求协议 RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA @@ -177,6 +185,9 @@ func (c *GinClient) GormMiddleware() gin.HandlerFunc { ResponseData: datatypes.JSON(responseBody), //【返回】数据 CostTime: endTime - startTime, //【系统】花费时间 }) + if err != nil { + log.Println("log.gormRecord:", err.Error()) + } } } }() diff --git a/utils/golog/gin_mongo.go b/utils/golog/gin_mongo.go index c2cbbe58..73645023 100644 --- a/utils/golog/gin_mongo.go +++ b/utils/golog/gin_mongo.go @@ -3,9 +3,11 @@ package golog import ( "bytes" "encoding/json" + "github.com/dtapps/go-library" "github.com/dtapps/go-library/utils/dorm" - "github.com/dtapps/go-library/utils/gorequest" "github.com/dtapps/go-library/utils/gotime" + "github.com/dtapps/go-library/utils/gotrace_id" + "github.com/dtapps/go-library/utils/gourl" "github.com/dtapps/go-library/utils/goxml" "github.com/gin-gonic/gin" "go.mongodb.org/mongo-driver/bson/primitive" @@ -42,6 +44,7 @@ type ginMongoLog struct { SystemHostName string `json:"system_host_name,omitempty" bson:"system_host_name,omitempty"` //【系统】主机名 SystemInsideIp string `json:"system_inside_ip,omitempty" bson:"system_inside_ip,omitempty"` //【系统】内网ip GoVersion string `json:"go_version,omitempty" bson:"go_version,omitempty"` //【程序】Go版本 + SdkVersion string `json:"sdk_version,omitempty" bson:"sdk_version,omitempty"` //【程序】Sdk版本 } // 记录日志 @@ -53,6 +56,8 @@ func (c *GinClient) mongoRecord(mongoLog ginMongoLog) error { } mongoLog.GoVersion = c.config.goVersion + mongoLog.SdkVersion = go_library.Version() + mongoLog.LogId = primitive.NewObjectID() _, err := c.mongoClient.Database(c.config.databaseName).Collection(c.config.collectionName).InsertOne(mongoLog) @@ -75,6 +80,7 @@ func (c *GinClient) MongoMiddleware() gin.HandlerFunc { // 获取 data, _ := ioutil.ReadAll(ginCtx.Request.Body) + // 复用 ginCtx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(data)) @@ -130,53 +136,53 @@ func (c *GinClient) MongoMiddleware() gin.HandlerFunc { } if len(jsonBody) > 0 { c.mongoRecord(ginMongoLog{ - TraceId: ginCtx.MustGet("trace_id").(string), //【系统】链编号 - RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间 - RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 - RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 - RequestApi: gorequest.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 - RequestMethod: ginCtx.Request.Method, //【请求】请求方式 - RequestProto: ginCtx.Request.Proto, //【请求】请求协议 - RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA - RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer - RequestBody: jsonBody, //【请求】请求主体 - RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数 - RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip - RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市 - RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域 - RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份 - RequestIpCity: requestClientIpCity, //【请求】请求客户端城市 - RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商 - RequestHeader: ginCtx.Request.Header, //【请求】请求头 - ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间 - ResponseCode: responseCode, //【返回】状态码 - ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据 - CostTime: endTime - startTime, //【系统】花费时间 + TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号 + RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间 + RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 + RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 + RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 + RequestMethod: ginCtx.Request.Method, //【请求】请求方式 + RequestProto: ginCtx.Request.Proto, //【请求】请求协议 + RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA + RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer + RequestBody: jsonBody, //【请求】请求主体 + RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数 + RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip + RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市 + RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域 + RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份 + RequestIpCity: requestClientIpCity, //【请求】请求客户端城市 + RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商 + RequestHeader: ginCtx.Request.Header, //【请求】请求头 + ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间 + ResponseCode: responseCode, //【返回】状态码 + ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据 + CostTime: endTime - startTime, //【系统】花费时间 }) } else { c.mongoRecord(ginMongoLog{ - TraceId: ginCtx.MustGet("trace_id").(string), //【系统】链编号 - RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间 - RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 - RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 - RequestApi: gorequest.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 - RequestMethod: ginCtx.Request.Method, //【请求】请求方式 - RequestProto: ginCtx.Request.Proto, //【请求】请求协议 - RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA - RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer - RequestBody: xmlBody, //【请求】请求主体 - RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数 - RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip - RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市 - RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域 - RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份 - RequestIpCity: requestClientIpCity, //【请求】请求客户端城市 - RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商 - RequestHeader: ginCtx.Request.Header, //【请求】请求头 - ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间 - ResponseCode: responseCode, //【返回】状态码 - ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据 - CostTime: endTime - startTime, //【系统】花费时间 + TraceId: gotrace_id.GetGinTraceId(ginCtx), //【系统】链编号 + RequestTime: gotime.SetCurrent(requestTime).Timestamp(), //【请求】时间 + RequestUri: host + ginCtx.Request.RequestURI, //【请求】请求链接 + RequestUrl: ginCtx.Request.RequestURI, //【请求】请求链接 + RequestApi: gourl.UriFilterExcludeQueryString(ginCtx.Request.RequestURI), //【请求】请求接口 + RequestMethod: ginCtx.Request.Method, //【请求】请求方式 + RequestProto: ginCtx.Request.Proto, //【请求】请求协议 + RequestUa: ginCtx.Request.UserAgent(), //【请求】请求UA + RequestReferer: ginCtx.Request.Referer(), //【请求】请求referer + RequestBody: xmlBody, //【请求】请求主体 + RequestUrlQuery: ginCtx.Request.URL.Query(), //【请求】请求URL参数 + RequestIp: ginCtx.ClientIP(), //【请求】请求客户端Ip + RequestIpCountry: requestClientIpCountry, //【请求】请求客户端城市 + RequestIpRegion: requestClientIpRegion, //【请求】请求客户端区域 + RequestIpProvince: requestClientIpProvince, //【请求】请求客户端省份 + RequestIpCity: requestClientIpCity, //【请求】请求客户端城市 + RequestIpIsp: requestClientIpIsp, //【请求】请求客户端运营商 + RequestHeader: ginCtx.Request.Header, //【请求】请求头 + ResponseTime: gotime.SetCurrent(gotime.Current().Time).Timestamp(), //【返回】时间 + ResponseCode: responseCode, //【返回】状态码 + ResponseData: c.jsonUnmarshal(responseBody), //【返回】数据 + CostTime: endTime - startTime, //【系统】花费时间 }) } } diff --git a/utils/golog/golog.go b/utils/golog/log.go similarity index 100% rename from utils/golog/golog.go rename to utils/golog/log.go diff --git a/utils/gorequest/http.go b/utils/gorequest/http.go index 2a6191f2..70779b50 100644 --- a/utils/gorequest/http.go +++ b/utils/gorequest/http.go @@ -2,11 +2,14 @@ package gorequest import ( "bytes" + "context" "crypto/tls" "encoding/json" "errors" "fmt" + "github.com/dtapps/go-library/utils/gostring" "github.com/dtapps/go-library/utils/gotime" + "github.com/dtapps/go-library/utils/gotrace_id" "io" "io/ioutil" "net/http" @@ -132,32 +135,32 @@ func (app *App) SetP12Cert(content *tls.Certificate) { } // Get 发起GET请求 -func (app *App) Get(uri ...string) (httpResponse Response, err error) { +func (app *App) Get(ctx context.Context, uri ...string) (httpResponse Response, err error) { if len(uri) == 1 { app.Uri = uri[0] } // 设置请求方法 app.httpMethod = http.MethodGet - return request(app) + return request(app, ctx) } // Post 发起POST请求 -func (app *App) Post(uri ...string) (httpResponse Response, err error) { +func (app *App) Post(ctx context.Context, uri ...string) (httpResponse Response, err error) { if len(uri) == 1 { app.Uri = uri[0] } // 设置请求方法 app.httpMethod = http.MethodPost - return request(app) + return request(app, ctx) } // Request 发起请求 -func (app *App) Request() (httpResponse Response, err error) { - return request(app) +func (app *App) Request(ctx context.Context) (httpResponse Response, err error) { + return request(app, ctx) } // 请求接口 -func request(app *App) (httpResponse Response, err error) { +func request(app *App, ctx context.Context) (httpResponse Response, err error) { // 赋值 httpResponse.RequestTime = gotime.Current().Time @@ -190,7 +193,10 @@ func request(app *App) (httpResponse Response, err error) { } } + // SDK版本 httpResponse.RequestHeader.Set("Sdk-User-Agent", fmt.Sprintf(userAgentFormat, runtime.GOOS, runtime.Version())) + + // 请求类型 switch app.httpContentType { case httpParamsModeJson: httpResponse.RequestHeader.Set("Content-Type", "application/json") @@ -200,6 +206,13 @@ func request(app *App) (httpResponse Response, err error) { httpResponse.RequestHeader.Set("Content-Type", "text/xml") } + // 跟踪编号 + traceId := gotrace_id.GetTraceIdContext(ctx) + if traceId == "" { + traceId = gostring.GetUuId() + } + httpResponse.RequestHeader.Set("X-Request-Id", traceId) + // 请求内容 var reqBody io.Reader diff --git a/utils/gorequest/ip.go b/utils/gorequest/ip.go index 05514cb4..b2d65b01 100644 --- a/utils/gorequest/ip.go +++ b/utils/gorequest/ip.go @@ -10,7 +10,7 @@ import ( // 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理(nginx 或 haproxy)可以正常工作。 func ClientIp(r *http.Request) string { - // cloudflare + // CloudFlare CfConnectingIp := strings.TrimSpace(r.Header.Get("Cf-Connecting-Ip")) if CfConnectingIp != "" { return CfConnectingIp diff --git a/utils/gorequest/url.go b/utils/gorequest/url.go deleted file mode 100644 index 0d3ad79f..00000000 --- a/utils/gorequest/url.go +++ /dev/null @@ -1,70 +0,0 @@ -package gorequest - -import ( - "net/url" - "strings" -) - -// ResponseUrlParse 返回参数 -type ResponseUrlParse struct { - Uri string `json:"uri"` // URI - Urn string `json:"urn"` // URN - Url string `json:"url"` // URL - Scheme string `json:"scheme"` // 协议 - Host string `json:"host"` // 主机 - Hostname string `json:"hostname"` // 主机名 - Port string `json:"port"` // 端口 - Path string `json:"path"` // 路径 - RawQuery string `json:"raw_query"` // 参数 ? - Fragment string `json:"fragment"` // 片段 # -} - -// UriParse 解析URl -func UriParse(input string) (resp ResponseUrlParse) { - parse, err := url.Parse(input) - if err != nil { - return - } - resp.Uri = input - resp.Urn = parse.Host + parse.Path - resp.Url = parse.Scheme + "://" + parse.Host + parse.Path - resp.Scheme = parse.Scheme - resp.Host = parse.Host - resp.Hostname = parse.Hostname() - resp.Port = parse.Port() - resp.Path = parse.Path - resp.RawQuery = parse.RawQuery - resp.Fragment = parse.Fragment - return -} - -// UriFilterExcludeQueryString 过滤掉url中的参数 -func UriFilterExcludeQueryString(uri string) string { - URL, _ := url.Parse(uri) - clearUri := strings.ReplaceAll(uri, URL.RawQuery, "") - clearUri = strings.TrimRight(clearUri, "?") - return strings.TrimRight(clearUri, "/") -} - -// LenCode 编码 -func LenCode(s string) string { - escape := url.QueryEscape(s) - return escape -} - -// DeCode 解码 -func DeCode(s string) string { - unescape, _ := url.QueryUnescape(s) - return unescape -} - -// ParseQuery 获取URL参数 https://studygolang.com/articles/2876 -func ParseQuery(s string) map[string][]string { - u, err := url.Parse(s) - if err != nil { - return nil - } - urlParam := u.RawQuery - m, _ := url.ParseQuery(urlParam) - return m -} diff --git a/utils/gostorage/connom.go b/utils/gostorage/common.go similarity index 100% rename from utils/gostorage/connom.go rename to utils/gostorage/common.go diff --git a/utils/gostring/custom.go b/utils/gostring/custom.go new file mode 100644 index 00000000..550a5d6d --- /dev/null +++ b/utils/gostring/custom.go @@ -0,0 +1,203 @@ +package gostring + +import ( + "errors" + "fmt" + "github.com/dtapps/go-library/utils/gorandom" + "github.com/dtapps/go-library/utils/gotime" +) + +// GenerateId 生成18一编号 +func GenerateId(customId string) string { + currentTime := gotime.Current().Format() + one, err := generateIdOne(customId, currentTime) + if err == nil { + return one + } + two, err := generateIdTwo(customId, currentTime) + if err == nil { + return two + } + three, err := generateIdThree(customId, currentTime) + if err == nil { + return three + } + four, err := generateIdFour(customId, currentTime) + if err == nil { + return four + } + five, err := generateIdFive(customId, currentTime) + if err == nil { + return five + } + six, err := generateIdSix(customId) + return six +} + +// GenerateIdAndTime 生成18一编号 +func GenerateIdAndTime(customId, customTime string) string { + one, err := generateIdOne(customId, customTime) + if err == nil { + return one + } + two, err := generateIdTwo(customId, customTime) + if err == nil { + return two + } + three, err := generateIdThree(customId, customTime) + if err == nil { + return three + } + four, err := generateIdFour(customId, customTime) + if err == nil { + return four + } + five, err := generateIdFive(customId, customTime) + if err == nil { + return five + } + six, err := generateIdSix(customId) + return six +} + +// 生成18位时间[年月日时分]唯一编号 +func generateIdOne(customId, setTime string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度 + dataLength = 18 // 默认数据长度 + dateFormat = "200601021504" // 时间格式 + dateFormatLength = len(dateFormat) // 时间格式长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - (dateFormatLength + customIdLength) + + if (dateFormatLength+customIdLength > dataLength) || (dateFormatLength+customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s%s", customId, gotime.SetCurrentParse(setTime).SetFormat(dateFormat), gorandom.Numeric(newRandomLength)), nil +} + +// 生成18位时间[年月日时]唯一编号 +func generateIdTwo(customId, setTime string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度 + dataLength = 18 // 默认数据长度 + dateFormat = "2006010215" // 时间格式 + dateFormatLength = len(dateFormat) // 时间格式长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - (dateFormatLength + customIdLength) + + if (dateFormatLength+customIdLength > dataLength) || (dateFormatLength+customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s%s", customId, gotime.SetCurrentParse(setTime).SetFormat(dateFormat), gorandom.Numeric(newRandomLength)), nil +} + +// 生成18位时间[年月日]唯一编号 +func generateIdThree(customId, setTime string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度 + dataLength = 18 // 默认数据长度 + dateFormat = "20060102" // 时间格式 + dateFormatLength = len(dateFormat) // 时间格式长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - (dateFormatLength + customIdLength) + + if (dateFormatLength+customIdLength > dataLength) || (dateFormatLength+customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s%s", customId, gotime.SetCurrentParse(setTime).SetFormat(dateFormat), gorandom.Numeric(newRandomLength)), nil +} + +// 生成18位时间[年月]唯一编号 +func generateIdFour(customId, setTime string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度 + dataLength = 18 // 默认数据长度 + dateFormat = "200601" // 时间格式 + dateFormatLength = len(dateFormat) // 时间格式长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - (dateFormatLength + customIdLength) + + if (dateFormatLength+customIdLength > dataLength) || (dateFormatLength+customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s%s", customId, gotime.SetCurrentParse(setTime).SetFormat(dateFormat), gorandom.Numeric(newRandomLength)), nil +} + +// 生成18位时间[年]唯一编号 +func generateIdFive(customId, setTime string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度` + dataLength = 18 // 默认数据长度 + dateFormat = "2006" // 时间格式 + dateFormatLength = len(dateFormat) // 时间格式长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - (dateFormatLength + customIdLength) + + if (dateFormatLength+customIdLength > dataLength) || (dateFormatLength+customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s%s", customId, gotime.SetCurrentParse(setTime).SetFormat(dateFormat), gorandom.Numeric(newRandomLength)), nil +} + +// 生成18位随机唯一编号 +func generateIdSix(customId string) (string, error) { + + var ( + newRandomLength = 0 // 随机数据长度 + customIdLength = len(customId) // 自定义长度 + ) + + const ( + randomLength = 5 // 随机数据长度 + dataLength = 18 // 默认数据长度 + ) + + // 重新计算随机数据长度 + newRandomLength = dataLength - customIdLength + + if (customIdLength > dataLength) || (customIdLength == dataLength) || (newRandomLength < randomLength) { + return "", errors.New("没有满足条件") + } + return fmt.Sprintf("%v%s", customId, gorandom.Numeric(newRandomLength)), nil +} diff --git a/utils/gostring/only.go b/utils/gostring/only.go new file mode 100644 index 00000000..e2dfa57b --- /dev/null +++ b/utils/gostring/only.go @@ -0,0 +1,8 @@ +package gostring + +type Only struct { +} + +func NewOnly() *Only { + return &Only{} +} diff --git a/utils/gostring/gostring.go b/utils/gostring/string.go similarity index 100% rename from utils/gostring/gostring.go rename to utils/gostring/string.go diff --git a/utils/gostring/uuid.go b/utils/gostring/uuid.go new file mode 100644 index 00000000..d3c6e8af --- /dev/null +++ b/utils/gostring/uuid.go @@ -0,0 +1,18 @@ +package gostring + +import ( + "crypto/rand" + "fmt" + "time" +) + +// GetUuId 由 32 个十六进制数字组成,以 6 个组显示,由连字符 - 分隔 +func GetUuId() string { + unix32bits := uint32(time.Now().UTC().Unix()) + buff := make([]byte, 12) + numRead, err := rand.Read(buff) + if numRead != len(buff) || err != nil { + return "" + } + return fmt.Sprintf("%x-%x-%x-%x-%x-%x", unix32bits, buff[0:2], buff[2:4], buff[4:6], buff[6:8], buff[8:]) +} diff --git a/utils/gotime/gotime.go b/utils/gotime/gotime.go index 3bd7dfe0..9123a59e 100644 --- a/utils/gotime/gotime.go +++ b/utils/gotime/gotime.go @@ -36,42 +36,42 @@ func NewPro() Pro { } // BeforeSeconds 获取n秒前的时间 -func (p Pro) BeforeSeconds(seconds int) Pro { +func (p Pro) BeforeSeconds(seconds int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("-%ds", seconds)) p.Time = p.Time.Add(st) return p } // AfterSeconds 获取n秒后的时间 -func (p Pro) AfterSeconds(seconds int) Pro { +func (p Pro) AfterSeconds(seconds int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("+%ds", seconds)) p.Time = p.Time.Add(st) return p } // BeforeMinute 获取n分钟前的时间 -func (p Pro) BeforeMinute(seconds int) Pro { +func (p Pro) BeforeMinute(seconds int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("-%dm", seconds)) p.Time = p.Time.Add(st) return p } // AfterMinute 获取n分钟后的时间 -func (p Pro) AfterMinute(seconds int) Pro { +func (p Pro) AfterMinute(seconds int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("+%dm", seconds)) p.Time = p.Time.Add(st) return p } // BeforeHour 获取n小时前的时间 -func (p Pro) BeforeHour(hour int) Pro { +func (p Pro) BeforeHour(hour int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("-%dh", hour)) p.Time = p.Time.Add(st) return p } // AfterHour 获取n小时后的时间 -func (p Pro) AfterHour(hour int) Pro { +func (p Pro) AfterHour(hour int64) Pro { st, _ := time.ParseDuration(fmt.Sprintf("+%dh", hour)) p.Time = p.Time.Add(st) return p @@ -95,11 +95,11 @@ func (p Pro) SetFormat(layout string) string { } // Month 获取当前月 -func (p Pro) Month() int { +func (p Pro) Month() int64 { return p.MonthOfYear() } // MonthOfYear 获取本年的第几月 -func (p Pro) MonthOfYear() int { - return int(p.Time.In(p.loc).Month()) +func (p Pro) MonthOfYear() int64 { + return int64(p.Time.In(p.loc).Month()) } diff --git a/utils/gotime/today.go b/utils/gotime/today.go index b1a082ba..f19f505e 100644 --- a/utils/gotime/today.go +++ b/utils/gotime/today.go @@ -9,11 +9,8 @@ import ( // Current 获取当前的时间 func Current() Pro { - p := NewPro() - p.loc, p.Error = time.LoadLocation("Asia/Shanghai") - if p.Error != nil { // Docker部署golang应用时时区问题 https://www.ddhigh.com/2018/03/01/golang-docker-timezone.html log.Printf("【gotime】时区错误:%v\n", p.Error) @@ -21,17 +18,13 @@ func Current() Pro { } else { p.Time = time.Now().In(p.loc) } - return p } // SetCurrent 设置当前的时间 func SetCurrent(sTime time.Time) Pro { - p := NewPro() - p.Time = sTime - return p } @@ -43,19 +36,15 @@ func SetCurrentParse(str string) Pro { p.loc, p.Error = time.LoadLocation("Asia/Shanghai") layout := DateTimeFormat - if str == "" || str == "0" || str == "0000-00-00 00:00:00" || str == "0000-00-00" || str == "00:00:00" { return p } - if len(str) == 10 && strings.Count(str, "-") == 2 { layout = DateFormat } - if strings.Index(str, "T") == 10 { layout = RFC3339Format } - if _, err := strconv.ParseInt(str, 10, 64); err == nil { switch len(str) { case 8: @@ -64,29 +53,19 @@ func SetCurrentParse(str string) Pro { layout = ShortDateTimeFormat } } - location, _ := time.ParseInLocation(layout, str, p.loc) p.Time = location - return p } // SetCurrentUnix 设置当前的时间 Unix时间戳 func SetCurrentUnix(ts int64) Pro { - p := NewPro() - p.Time = time.Unix(ts, 0) - return p } -// Timestamp 今天此刻时间戳 -func (p Pro) Timestamp() int64 { - return p.Time.Unix() -} - // Now 今天此刻 func (p Pro) Now() time.Time { return p.Time @@ -107,6 +86,11 @@ func (p Pro) ToTimeFormat() string { return p.Time.Format(TimeFormat) } +// Timestamp 今天此刻时间戳 +func (p Pro) Timestamp() int64 { + return p.Time.Unix() +} + // TimestampWithSecond 今天此刻时间戳 func (p Pro) TimestampWithSecond() int64 { return p.Time.Unix() diff --git a/utils/gotime/tomorrow.go b/utils/gotime/tomorrow.go index bfada328..e91268f5 100644 --- a/utils/gotime/tomorrow.go +++ b/utils/gotime/tomorrow.go @@ -4,16 +4,12 @@ import "time" // Tomorrow 明天 func Tomorrow() Pro { - p := NewPro() - location, err := time.LoadLocation("Asia/Shanghai") - if err != nil { p.Time = time.Now().Add(time.Hour*8).AddDate(0, 0, +1) } else { p.Time = time.Now().In(location).AddDate(0, 0, +1) } - return p } diff --git a/utils/gotime/verification.go b/utils/gotime/verification.go new file mode 100644 index 00000000..ad800067 --- /dev/null +++ b/utils/gotime/verification.go @@ -0,0 +1,16 @@ +package gotime + +import "time" + +// Verification 验证字符串是否为时间 +func Verification(str, layout string) (resp time.Time, err error) { + loc, err := time.LoadLocation("Asia/Shanghai") + if err != nil { + return time.Time{}, err + } + location, err := time.ParseInLocation(layout, str, loc) + if err != nil { + return time.Time{}, err + } + return location, nil +} diff --git a/utils/gotime/yesterday.go b/utils/gotime/yesterday.go index de89489a..be1cd6c6 100644 --- a/utils/gotime/yesterday.go +++ b/utils/gotime/yesterday.go @@ -6,16 +6,12 @@ import ( // Yesterday 昨天 func Yesterday() Pro { - p := NewPro() - location, err := time.LoadLocation("Asia/Shanghai") - if err != nil { p.Time = time.Now().Add(time.Hour*8).AddDate(0, 0, -1) } else { p.Time = time.Now().In(location).AddDate(0, 0, -1) } - return p } diff --git a/utils/gotrace_id/context.go b/utils/gotrace_id/context.go new file mode 100644 index 00000000..d95d5a4b --- /dev/null +++ b/utils/gotrace_id/context.go @@ -0,0 +1,27 @@ +package gotrace_id + +import ( + "context" + "fmt" + "github.com/dtapps/go-library/utils/gostring" + "github.com/gin-gonic/gin" +) + +// CustomTraceIdContext 自定义设置跟踪编号上下文 +func CustomTraceIdContext() context.Context { + return context.WithValue(context.Background(), "trace_id", gostring.GetUuId()) +} + +// SetGinTraceIdContext 设置跟踪编号上下文 +func SetGinTraceIdContext(c *gin.Context) context.Context { + return context.WithValue(context.Background(), "trace_id", GetGinTraceId(c)) +} + +// GetTraceIdContext 通过上下文获取跟踪编号 +func GetTraceIdContext(ctx context.Context) string { + traceId := fmt.Sprintf("%v", ctx.Value("trace_id")) + if len(traceId) <= 0 { + return "" + } + return traceId +} diff --git a/utils/gotrace_id/gin_use.go b/utils/gotrace_id/gin_use.go new file mode 100644 index 00000000..ab2ee5e8 --- /dev/null +++ b/utils/gotrace_id/gin_use.go @@ -0,0 +1,29 @@ +package gotrace_id + +import ( + "fmt" + "github.com/dtapps/go-library/utils/gostring" + "github.com/gin-gonic/gin" +) + +// SetGinTraceId 设置跟踪编号 https://www.jianshu.com/p/2a1a74ad3c3a +func SetGinTraceId() gin.HandlerFunc { + return func(c *gin.Context) { + requestId := c.Request.Header.Get("X-Request-Id") + if requestId == "" { + requestId = gostring.GetUuId() + } + c.Set("trace_id", requestId) + c.Writer.Header().Set("X-Request-Id", requestId) + c.Next() + } +} + +// GetGinTraceId 通过gin中间件获取跟踪编号 +func GetGinTraceId(c *gin.Context) string { + traceId := fmt.Sprintf("%v", c.MustGet("trace_id")) + if len(traceId) <= 0 { + return "" + } + return traceId +} diff --git a/utils/gourl/gourl.go b/utils/gourl/gourl.go index 2c2d2cf7..5e93b491 100644 --- a/utils/gourl/gourl.go +++ b/utils/gourl/gourl.go @@ -1,12 +1,51 @@ package gourl import ( - "io" - "net/http" "net/url" - "os" + "strings" ) +// ResponseUrlParse 返回参数 +type ResponseUrlParse struct { + Uri string `json:"uri"` // URI + Urn string `json:"urn"` // URN + Url string `json:"url"` // URL + Scheme string `json:"scheme"` // 协议 + Host string `json:"host"` // 主机 + Hostname string `json:"hostname"` // 主机名 + Port string `json:"port"` // 端口 + Path string `json:"path"` // 路径 + RawQuery string `json:"raw_query"` // 参数 ? + Fragment string `json:"fragment"` // 片段 # +} + +// UriParse 解析URl +func UriParse(input string) (resp ResponseUrlParse) { + parse, err := url.Parse(input) + if err != nil { + return + } + resp.Uri = input + resp.Urn = parse.Host + parse.Path + resp.Url = parse.Scheme + "://" + parse.Host + parse.Path + resp.Scheme = parse.Scheme + resp.Host = parse.Host + resp.Hostname = parse.Hostname() + resp.Port = parse.Port() + resp.Path = parse.Path + resp.RawQuery = parse.RawQuery + resp.Fragment = parse.Fragment + return +} + +// UriFilterExcludeQueryString 过滤掉url中的参数 +func UriFilterExcludeQueryString(uri string) string { + URL, _ := url.Parse(uri) + clearUri := strings.ReplaceAll(uri, URL.RawQuery, "") + clearUri = strings.TrimRight(clearUri, "?") + return strings.TrimRight(clearUri, "/") +} + // LenCode 编码 func LenCode(s string) string { escape := url.QueryEscape(s) @@ -29,17 +68,3 @@ func ParseQuery(s string) map[string][]string { m, _ := url.ParseQuery(urlParam) return m } - -// QueryHeaders 获取Headers参数 https://blog.csdn.net/qq_31387691/article/details/109312920 -func QueryHeaders(url string) map[string][]string { - client := &http.Client{} - reqest, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil - } - response, _ := client.Do(reqest) - stdout := os.Stdout - _, err = io.Copy(stdout, response.Body) - headers := response.Header - return headers -} diff --git a/utils/validator/validator.go b/utils/govalidator/validator.go similarity index 99% rename from utils/validator/validator.go rename to utils/govalidator/validator.go index 4b591381..0f4d0415 100644 --- a/utils/validator/validator.go +++ b/utils/govalidator/validator.go @@ -1,4 +1,4 @@ -package validator +package govalidator import ( "github.com/gin-gonic/gin/binding" diff --git a/utils/goverify/get.go b/utils/goverify/get.go new file mode 100644 index 00000000..d0b24bab --- /dev/null +++ b/utils/goverify/get.go @@ -0,0 +1,32 @@ +package goverify + +// 运营商名称 +var typeName = map[string]string{ + Mobile: "移动", + Unicom: "联通", + Telecom: "电信", + Broadnet: "广电", + Virtual: "虚拟", +} + +// GetTypeName 获取运营商类型名称 +func GetTypeName(Type string) string { + return typeName[Type] +} + +// GetType 获取运营商类型 +func GetType(name string) (Type string) { + switch name { + case "移动", "移动运营商", "中国移动", "中国移动运营商": + return Mobile + case "联通", "联通运营商", "中国联通", "中国联通运营商": + return Unicom + case "电信", "电信运营商", "中国电信", "中国电信运营商": + return Telecom + case "广电", "广电运营商", "中国广电", "中国广电运营商": + return Broadnet + case "虚拟", "虚拟运营商": + return Virtual + } + return Type +} diff --git a/utils/goverify/gopreg.go b/utils/goverify/gopreg.go new file mode 100644 index 00000000..a4c9155a --- /dev/null +++ b/utils/goverify/gopreg.go @@ -0,0 +1,100 @@ +package goverify + +import ( + "regexp" +) + +const ( + Mobile = "mobile" // 中国移动 + Unicom = "unicom" // 中国联通 + Telecom = "telecom" // 中国电信 + Broadnet = "broadnet" // 中国广电 + Virtual = "virtual" // 虚拟 +) + +// ChinaMobile 验证手机号码 +// https://baike.baidu.com/item/%E7%94%B5%E8%AF%9D%E5%8F%B7%E7%A0%81/1417271 +// https://zh.wikipedia.org/wiki/%E4%B8%AD%E5%9B%BD%E5%A4%A7%E9%99%86%E7%A7%BB%E5%8A%A8%E7%BB%88%E7%AB%AF%E9%80%9A%E4%BF%A1%E5%8F%B7%E7%A0%81#cite_note-2 +// https://www.qqzeng.com/tongji.html +func ChinaMobile(number string) (status bool, operator string) { + status = ChinaMobileNumber(number) // 中国移动运营商 + if status { + return status, Mobile + } + status = ChinaUnicomNumber(number) // 中国联通运营商 + if status { + return status, Unicom + } + status = ChinaTelecomNumber(number) // 中国电信运营商 + if status { + return status, Telecom + } + status = ChinaBroadnetNumber(number) // 中国广电运营商 + if status { + return status, Broadnet + } + status = ChinaVirtualNumber(number) // 虚拟运营商 + if status { + return status, Virtual + } + return +} + +// ChinaMobileNumber 验证中国移动手机号码 +// https://www.qqzeng.com/tongji.html +// 移动:134 135 136 137 138 139 147 148 150 151 152 157 158 159 172 178 182 183 184 187 188 195 197 198 +func ChinaMobileNumber(number string) bool { + regular := "^[1](([3][4-9])|([4][7-8])|([5][0-2,7-9])|([7][2,8])|([8][2-4,7-8])|([9][5,7-8]))[0-9]{8}$" + reg := regexp.MustCompile(regular) + return reg.MatchString(number) +} + +// ChinaUnicomNumber 验证中国联通手机号码 +// https://www.qqzeng.com/tongji.html +// 联通:130 131 132 145 146 155 156 166 167 171 175 176 185 186 196 +func ChinaUnicomNumber(number string) bool { + regular := "^[1](([3][0-2])|([4][5-6])|([5][5-6])|([6][6-7])|([7][1,5-6])|([8][5-6])|([9][6]))[0-9]{8}$" + reg := regexp.MustCompile(regular) + return reg.MatchString(number) +} + +// ChinaTelecomNumber 验证中国电信手机号码 +// https://www.qqzeng.com/tongji.html +// 电信:133 149 153 173 174 177 180 181 189 190 191 193 199 +func ChinaTelecomNumber(number string) bool { + regular := "^[1](([3][3])|([4][9])|([5][3])|([7][3-4,7])||([8][0-1,9])|([9][0-1,3,9]))[0-9]{8}$" + reg := regexp.MustCompile(regular) + return reg.MatchString(number) +} + +// ChinaBroadnetNumber 验证中国广电手机号码 +// https://www.qqzeng.com/tongji.html +// 广电:192 +func ChinaBroadnetNumber(number string) bool { + regular := "^[1](([9][2]))[0-9]{8}$" + reg := regexp.MustCompile(regular) + return reg.MatchString(number) +} + +// ChinaVirtualNumber 验证虚拟运营商手机号码 +// https://www.qqzeng.com/tongji.html +// 移动/联通/电信: 162 165 167 170 171 +func ChinaVirtualNumber(number string) bool { + regular := "^[1](([6][2,5,7])|([7][0-1]))[0-9]{8}$" + reg := regexp.MustCompile(regular) + return reg.MatchString(number) +} + +// IdCard 验证身份证号码 +func IdCard(idCard string) bool { + regular := "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$" + reg := regexp.MustCompile(regular) + return reg.MatchString(idCard) +} + +// Email 验证邮箱号码 +func Email(email string) bool { + pattern := `^[0-9a-z][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}[0-9a-z]\.){1,4}[a-z]{2,4}$` + reg := regexp.MustCompile(pattern) + return reg.MatchString(email) +}