用golang写请求接口并对接chatgpt的方法怎么写
- 导入必要的包:
import (
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
)
- 定义请求结构体:
type Request struct {
Prompt string `json:"prompt"`
Length int `json:"length"`
}
- 定义响应结构体:
type Response struct {
Text string `json:"text"`
}
- 编写请求函数:
func RequestChatGPT(prompt string, length int) (string, error) {
url := "http://localhost:8000/chatgpt" // chatgpt接口地址
request := Request{Prompt: prompt, Length: length}
requestData, err := json.Marshal(request)
if err != nil {
return "", err
}
resp, err := http.Post(url, "application/json", bytes.NewBuffer(requestData))
if err != nil {
return "", err
}
defer resp.Body.Close()
responseData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var response Response
err = json.Unmarshal(responseData, &response)
if err != nil {
return "", err
}
return response.Text, nil
}
- 调用函数,并处理返回结果:
text, err := RequestChatGPT("Hi, how are you?", 50)
if err != nil {
fmt.Println("Request error:", err)
}
fmt.Println("Response text:", text)
注意:上述代码只是一个示例,需要根据实际情况进行修改。同时,chatgpt接口地址需要根据实际情况进行修改。
原文地址: https://www.cveoy.top/t/topic/Cwe 著作权归作者所有。请勿转载和采集!