package worker import ( "bytes" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "strings" "videoplayer/proto" ) var client *http.Client // 初始化 func InitReq() { client = &http.Client{} } // 发起post请求 func Post(url string, bodyType string, body string) (*http.Response, error) { req, err := http.NewRequest("POST", url, nil) if err != nil { return nil, err } req.Header.Set("Content-Type", bodyType) req.Body = io.NopCloser(strings.NewReader(body)) return client.Do(req) } // 发送到机器人 func SendToRobot(url string, body string) (map[string]interface{}, error) { resp, err := Post(url, "application/json", body) if err != nil { return nil, err } defer resp.Body.Close() m := make(map[string]interface{}) err = json.NewDecoder(resp.Body).Decode(&m) if err != nil { return nil, err } return m, nil } // 生成补全的函数 func GenerateCompletion(url, prompt string, model string) (map[string]interface{}, error) { data := map[string]interface{}{ "model": model, "prompt": prompt, "stream": false, } jsonData, err := json.Marshal(data) if err != nil { return nil, err } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") client_ := &http.Client{} resp, err := client_.Do(req) if err != nil { return nil, err } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } var result map[string]interface{} err = json.Unmarshal(body, &result) if err != nil { return nil, err } return result, nil } // 获取同步数据通用方法 func SyncDataFromMasterReq(url string, token string) proto.UserSync { //从接口获取数据 req, err := http.NewRequest("POST", url, nil) if err != nil { return proto.UserSync{} } req.Header.Set("token", token) client := &http.Client{} //获取数据 resp, err := client.Do(req) if err != nil { return proto.UserSync{} } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return proto.UserSync{} } var result map[string]interface{} err = json.Unmarshal(body, &result) if err != nil { return proto.UserSync{} } fmt.Println("SyncDataFromMasterReq result:", result) if result["code"].(float64) != 0 { return proto.UserSync{} } var userSync proto.UserSync err = json.Unmarshal([]byte(result["data"].(string)), &userSync) if err != nil { return proto.UserSync{} } return userSync }