Integration with ChatGPT API in Go: From Idea to Working Code

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why Go and ChatGPT Are the Perfect Duo?

\n

Have you ever wondered how quickly you can "teach" your Go program to communicate with a user like a real person? Or maybe you want to automate content generation, create an intelligent assistant, or simply add a "special touch" to your service? Integration with the ChatGPT API in Go is not just a trendy fad, but a powerful tool that opens doors to the world of artificial intelligence. Go, with its speed and simplicity, is ideal for creating fast and reliable requests to neural networks. In this article, we will not just cover the theory, but write real code that you can immediately use in your projects.

\n\n

Laying the Groundwork: What Do You Need to Start?

\n

Before diving into the code, let's make sure we have everything we need. You will need:

\n
    \n
  • Installed Go (version 1.21 or higher to use all modern features).
  • \n
  • OpenAI API key. You can get it on the OpenAI platform. Treat it like your bank card password — keep it secret!
  • \n
  • Basic understanding of HTTP requests and data structures in Go.
  • \n
\n

We will write all the code from the article in a single file main.go to keep the structure simple. Let's go!

\n\n

Step 1: Creating an HTTP Client and Sending the First Request

\n

The heart of our integration will be the standard net/http package. It is lightweight, fast, and requires no third-party dependencies. Our task is to send a POST request to the endpoint https://api.openai.com/v1/chat/completions with the correct body and headers.

\n\n

Request Structure

\n

The ChatGPT API expects JSON in a specific format. Let's create Go structures that exactly match this format:

\n
package main\n\nimport (\n    "bytes"\n    "encoding/json"\n    "fmt"\n    "io"\n    "net/http"\n    "os"\n)\n\ntype ChatMessage struct {\n    Role    string `json:"role"`\n    Content string `json:"content"`\n}\n\ntype ChatRequest struct {\n    Model    string        `json:"model"`\n    Messages []ChatMessage `json:"messages"`\n}\n\ntype ChatResponse struct {\n    Choices []struct {\n        Message ChatMessage `json:"message"`\n    } `json:"choices"`\n}
\n

Notice the json:"..." tags. They ensure that Go correctly "packs" (serializes) our data into JSON that OpenAI will understand.

\n\n

The Sender Function

\n

Now let's write a function that handles all the "dirty" work: forms the request, sends it, and parses the response.

\n
func askChatGPT(apiKey, prompt string) (string, error) {\n    reqBody := ChatRequest{\n        Model: "gpt-3.5-turbo",\n        Messages: []ChatMessage{\n            {Role: "user", Content: prompt},\n        },\n    }\n\n    jsonData, err := json.Marshal(reqBody)\n    if err != nil {\n        return "", fmt.Errorf("marshaling error: %w", err)\n    }\n\n    request, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))\n    if err != nil {\n        return "", fmt.Errorf("request creation error: %w", err)\n    }\n\n    request.Header.Set("Content-Type", "application/json")\n    request.Header.Set("Authorization", "Bearer "+apiKey)\n\n    client := &http.Client{}\n    response, err := client.Do(request)\n    if err != nil {\n        return "", fmt.Errorf("request execution error: %w", err)\n    }\n    defer response.Body.Close()\n\n    body, err := io.ReadAll(response.Body)\n    if err != nil {\n        return "", fmt.Errorf("response reading error: %w", err)\n    }\n\n    // Check the status code\n    if response.StatusCode != http.StatusOK {\n        return "", fmt.Errorf("API returned an error: %s, body: %s", response.Status, string(body))\n    }\n\n    var chatResp ChatRes                

Blogs

Book Recommendations