Go

Go net/http with an OpenAI-compatible uncensored API

Call Abliterator from Go with only the standard library: a JSON chat request, an SSE stream reader with bufio, and an http.Handler that relays tokens to browsers.

Reviewed Gonet/http

Quick answer

POST JSON to https://abliterator.ai/v1/chat/completions with an Authorization: Bearer header from os.Getenv("ABL_API_KEY"). For streaming, set "stream": true and read data: lines with a bufio.Scanner.

Go needs no SDK for Abliterator: Chat Completions is one JSON POST, and streaming is Server-Sent Events that bufio can read. The request and response fields are in /docs/chat-completions; the Go side uses net/http only. All three programs pass go vet and were run with Go 1.25 against a stand-in server.

Setup

mkdir ablgo && cd ablgo && go mod init example.com/ablgo
export ABL_API_KEY="sk-abl-v1-..."

One request

package main

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

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

type chatResponse struct {
	Choices []struct {
		Message message `json:"message"`
	} `json:"choices"`
	Usage struct {
		PromptTokens     int     `json:"prompt_tokens"`
		CompletionTokens int     `json:"completion_tokens"`
		Cost             float64 `json:"cost"`
	} `json:"usage"`
}

func main() {
	body, _ := json.Marshal(map[string]any{
		"model":      "kimi-k3.1-pro-abliterated",
		"max_tokens": 800,
		"messages": []message{
			{Role: "system", Content: "You are a Go security reviewer."},
			{Role: "user", Content: "What are the risks of using math/rand for session tokens, and what should I use?"},
		},
	})
	req, err := http.NewRequest("POST", "https://abliterator.ai/v1/chat/completions", bytes.NewReader(body))
	if err != nil {
		log.Fatal(err)
	}
	req.Header.Set("Authorization", "Bearer "+os.Getenv("ABL_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 5 * time.Minute}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		var e struct {
			Error struct{ Message string } `json:"error"`
		}
		json.NewDecoder(resp.Body).Decode(&e)
		log.Fatalf("abliterator %d: %s (retry after %q)", resp.StatusCode, e.Error.Message, resp.Header.Get("Retry-After"))
	}

	var out chatResponse
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		log.Fatal(err)
	}
	fmt.Println(out.Choices[0].Message.Content)
	fmt.Printf("%d in, %d out, $%.6f, generation %s\n", out.Usage.PromptTokens, out.Usage.CompletionTokens,
		out.Usage.Cost, resp.Header.Get("X-Abl-Generation-Id"))
}

Set a client timeout. http.DefaultClient has none, so a stalled connection would hang forever.

Read a stream

Each event is a data: {json} line; the stream ends with data: [DONE]. The last JSON event has an empty choices array and the usage:

package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
)

type chunk struct {
	Choices []struct {
		Delta struct {
			Content string `json:"content"`
		} `json:"delta"`
	} `json:"choices"`
	Usage *struct {
		CompletionTokens int     `json:"completion_tokens"`
		Cost             float64 `json:"cost"`
	} `json:"usage"`
}

func main() {
	body, _ := json.Marshal(map[string]any{
		"model":    "deepseek-v4.1-flash-abliterated",
		"stream":   true,
		"messages": []map[string]string{{"role": "user", "content": "Explain how TLS certificate pinning works in mobile apps."}},
	})
	req, _ := http.NewRequest("POST", "https://abliterator.ai/v1/chat/completions", bytes.NewReader(body))
	req.Header.Set("Authorization", "Bearer "+os.Getenv("ABL_API_KEY"))
	req.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	sc := bufio.NewScanner(resp.Body)
	sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
	for sc.Scan() {
		data, ok := strings.CutPrefix(sc.Text(), "data: ")
		if !ok || data == "[DONE]" {
			continue
		}
		var c chunk
		if err := json.Unmarshal([]byte(data), &c); err != nil {
			log.Fatal(err)
		}
		if len(c.Choices) > 0 {
			fmt.Print(c.Choices[0].Delta.Content)
		}
		if c.Usage != nil {
			fmt.Printf("\n[%d tokens, $%.6f]\n", c.Usage.CompletionTokens, c.Usage.Cost)
		}
	}
	if err := sc.Err(); err != nil {
		log.Fatal(err)
	}
}

Raise the scanner buffer as shown. The default 64 KB line limit is too small for large tool-call arguments.

Relay the stream from an http.Handler

A handler can forward Abliterator's events to the browser byte for byte. Using r.Context() for the upstream request means a closed tab cancels the generation:

package main

import (
	"bytes"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
)

func chat(w http.ResponseWriter, r *http.Request) {
	var in struct {
		Messages []map[string]string `json:"messages"`
	}
	if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20)).Decode(&in); err != nil {
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}
	body, _ := json.Marshal(map[string]any{"model": "kimi-k3.1-pro-abliterated", "stream": true, "messages": in.Messages})
	up, _ := http.NewRequestWithContext(r.Context(), "POST", "https://abliterator.ai/v1/chat/completions", bytes.NewReader(body))
	up.Header.Set("Authorization", "Bearer "+os.Getenv("ABL_API_KEY"))
	up.Header.Set("Content-Type", "application/json")

	resp, err := http.DefaultClient.Do(up)
	if err != nil {
		http.Error(w, "upstream unavailable", http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
		return
	}

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	rc := http.NewResponseController(w)
	buf := make([]byte, 4096)
	for {
		n, err := resp.Body.Read(buf)
		if n > 0 {
			w.Write(buf[:n])
			rc.Flush()
		}
		if err != nil {
			return
		}
	}
}

func main() {
	http.HandleFunc("POST /api/chat", chat)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

http.NewResponseController(w).Flush() pushes each read to the client immediately; without flushing, net/http buffers the response.

Troubleshooting

  • 404. The URL must be https://abliterator.ai/v1/chat/completions. https://abliterator.ai/v1 already includes /v1.
  • bufio.Scanner: token too long. Raise the buffer with sc.Buffer, as in the stream example.
  • The browser gets everything at once. Flush after each write, and make sure middleware (gzip, some loggers) does not wrap the ResponseWriter in a way that hides Flush.
  • Long streams are cut off partway. A server WriteTimeout applies to the whole response, stream included. Leave it unset for streaming routes, or set a per-request deadline with rc.SetWriteDeadline.
  • 429 with Retry-After. Read the header (seconds) and back off; the first example prints it. Limits per plan are on /pricing.

Frequently asked questions

Why not use an SDK in Go?

You can: the official openai-go client accepts option.WithBaseURL("https://abliterator.ai/v1"). The standard library is enough for Chat Completions, though, and avoids a dependency in small services and CLIs.

How do I cancel a stream when the browser disconnects?

Build the upstream request with the incoming request's context (r.Context()). When the client goes away the context is cancelled, the upstream body read fails, and Abliterator stops generating.

Where is the request's cost?

Non-streaming responses carry usage.cost in the JSON body and an X-Abl-Cost-Usd header. Streams put usage, including cost, in the final event before [DONE].