SDKs

Go

Thunderbit Open API 的地道 Go 写法

net/http + encoding/json 就够,不需要 SDK。高并发场景配合 Goroutine 工作池,或用 golang.org/x/sync/errgroup

Client

package thunderbit

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

const API = "https://openapi.thunderbit.com/openapi/v1"

type Client struct {
    HTTP *http.Client
    Key  string
}

func New() *Client {
    return &Client{HTTP: http.DefaultClient, Key: os.Getenv("THUNDERBIT_API_KEY")}
}

func (c *Client) post(path string, body any, out any) error {
    raw, _ := json.Marshal(body)
    req, _ := http.NewRequest("POST", API+path, bytes.NewReader(raw))
    req.Header.Set("Authorization", "Bearer "+c.Key)
    req.Header.Set("Content-Type", "application/json")
    resp, err := c.HTTP.Do(req)
    if err != nil { return err }
    defer resp.Body.Close()
    if resp.StatusCode >= 400 {
        b, _ := io.ReadAll(resp.Body)
        return fmt.Errorf("thunderbit: %s: %s", resp.Status, b)
    }
    return json.NewDecoder(resp.Body).Decode(out)
}

Distill 一个页面

type DistillResp struct {
    Data struct { Markdown string `json:"markdown"` } `json:"data"`
}

c := New()
var out DistillResp
if err := c.post("/distill",
    map[string]any{"url": "https://thunderbit.com/playground"}, &out); err != nil {
    panic(err)
}
fmt.Println(out.Data.Markdown)

小贴士

  • 多个 Goroutine 间复用同一个 *http.Client —— 它是并发安全的,还能复用连接
  • 永远记得关闭响应体(defer resp.Body.Close()),否则会泄漏文件描述符
  • URL 数量超过 10 个时,优先用 /batch/distill —— 详见 Batch Job Lifecycle

官方 Go SDK 正在开发中,敬请期待。