package lib import ( "encoding/json" "fmt" "io/ioutil" "log" "net/http" "strings" ) type BaiduCheck struct { API_KEY, SECRET_KEY string } func (this *BaiduCheck) Check(query string) (string, error) { url := "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=" + this.GetAccessToken() payload := strings.NewReader(fmt.Sprintf("text=%s", query)) client := &http.Client{} req, err := http.NewRequest("POST", url, payload) if err != nil { log.Println(err) return "", err } req.Header.Add("Content-Type", "application/x-www-form-urlencoded") req.Header.Add("Accept", "application/json") res, err := client.Do(req) if err != nil { log.Println(err) return "", err } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { log.Println(err) return "", err } return string(body), nil } func (this *BaiduCheck) GetAccessToken() string { url := "https://aip.baidubce.com/oauth/2.0/token" postData := fmt.Sprintf("grant_type=client_credentials&client_id=%s&client_secret=%s", this.API_KEY, this.SECRET_KEY) resp, err := http.Post(url, "application/x-www-form-urlencoded", strings.NewReader(postData)) if err != nil { fmt.Println(err) return "" } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return "" } accessTokenObj := map[string]string{} json.Unmarshal([]byte(body), &accessTokenObj) return accessTokenObj["access_token"] }