package baidubce import ( "encoding/json" "errors" "fmt" "goskeleton/app/global/my_errors" "goskeleton/app/global/variable" "io" "net/http" "strings" ) /** * 使用 AK,SK 生成鉴权签名(Access Token) * @return string 鉴权签名信息(Access Token) */ func GetAccessToken() string { url := "https://aip.baidubce.com/oauth/2.0/token" API_KEY := variable.ConfigYml.GetString("BaiduCE.ApiKey") SECRET_KEY := variable.ConfigYml.GetString("BaiduCE.SecretKey") postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", API_KEY, SECRET_KEY) resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData)) if err != nil { variable.ZapLog.Error(my_errors.ErrorBaiduCEGetTokenFail + err.Error()) return "" } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { variable.ZapLog.Error(my_errors.ErrorBaiduCEGetTokenFail + err.Error()) return "" } accessTokenObj := map[string]any{} _ = json.Unmarshal([]byte(body), &accessTokenObj) return accessTokenObj["access_token"].(string) } func DecodeResBody(res *http.Response, flag string) (mbody map[string]interface{}, err error) { body, err := io.ReadAll(res.Body) if err != nil { variable.ZapLog.Error(my_errors.ErrorBaiduCEPostFail + flag + ", " + err.Error()) return nil, err } // json 格式的 body var jbody interface{} fmt.Println(string(body)) err = json.Unmarshal(body, &jbody) if err != nil { variable.ZapLog.Error(my_errors.ErrorBaiduCEPostFail + flag + ", " + err.Error()) return nil, err } mbody = jbody.(map[string]interface{}) err_str, _ := mbody["error_msg"].(string) if err_str != "" { variable.ZapLog.Error(my_errors.ErrorBaiduCEPostFail + flag + ", " + err_str) err = errors.New(err_str) return nil, err } return mbody, err }