DEVSAIO

Call AI models from Go with net/http

A small, dependency-free Go client for chat completions with typed requests and responses.

DEVSAIO team · 2 min read
Share on X

Go's standard library is all you need.

go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

type Msg struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type ChatReq struct {
	Model     string `json:"model"`
	Messages  []Msg  `json:"messages"`
	MaxTokens int    `json:"max_tokens,omitempty"`
}

type ChatResp struct {
	Choices []struct {
		Message Msg `json:"message"`
	} `json:"choices"`
	Error *struct {
		Message string `json:"message"`
	} `json:"error"`
}

var client = &http.Client{Timeout: 120 * time.Second}

func Chat(model string, msgs []Msg) (string, error) {
	body, _ := json.Marshal(ChatReq{Model: model, Messages: msgs, MaxTokens: 800})
	req, _ := http.NewRequest("POST", "https://devsaio.lol/v1/chat/completions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("DEVSAIO_API_KEY"))
	req.Header.Set("Content-Type", "application/json")
	res, err := client.Do(req)
	if err != nil {
		return "", err
	}
	defer res.Body.Close()
	var out ChatResp
	if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
		return "", err
	}
	if res.StatusCode != 200 || len(out.Choices) == 0 {
		if out.Error != nil {
			return "", fmt.Errorf("status %d: %s", res.StatusCode, out.Error.Message)
		}
		return "", fmt.Errorf("status %d", res.StatusCode)
	}
	return out.Choices[0].Message.Content, nil
}

func main() {
	answer, err := Chat("claude-sonnet-4-6", []Msg{{Role: "user", Content: "Explain goroutines in one paragraph."}})
	if err != nil {
		panic(err)
	}
	fmt.Println(answer)
}

Tips

  • Reuse one http.Client; it pools connections.
  • For streaming, set "stream": true and read the body line by line with bufio.Scanner, handling lines that start with data: .
  • Community libraries such as openai-go also accept a custom base URL if you prefer an SDK.
Try it with one API key

Claude, GPT, Gemini, DeepSeek, image and video models through one OpenAI- and Anthropic-compatible endpoint. Prepaid, pay only for what you use.

Keep reading