package main import ( "fmt" "io/ioutil" "net/http" "strings" ) func main() { // 定义 API 端点和请求参数 apiEndpoint := "https://api.openai.com/v1/engines/davinci-codex/completions" apiKey := "你的KEY" prompt := "Hello, ChatGPT!" maxTokens := "5" // 创建 POST 请求主体 requestBody := strings.NewReader(`{ "prompt": "` + prompt + `", "max_tokens": ` + maxTokens + ` }`) // 创建 HTTP 请求 req, err := http.NewRequest("POST", apiEndpoint, requestBody) if err != nil { panic(err) } // 添加请求头 req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+apiKey) // 发送请求 client := &http.Client{} resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close() // 读取响应主体 respBody, err := ioutil.ReadAll(resp.Body) if err != nil { panic(err) } // 输出响应 fmt.Println(string(respBody)) }
有问题请加博主微信进行沟通!
全部评论