You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package baidubce
import (
"encoding/json"
"errors"
"fmt"
"goskeleton/app/global/my_errors"
"goskeleton/app/global/variable"
"io"
"net/http"
"strings"
)
/**
* 使用 AKSK 生成鉴权签名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
}