SDKs

Go

Thunderbit Open API 的 Go 地道寫法

net/http + encoding/json,不需要 SDK。要高並發,搭配 Goroutine worker pool 或 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 —— 它是執行緒安全的,且能共用連線池
  • 一定要關閉 response body(defer resp.Body.Close()),否則會洩漏 FD
  • URL 數量達 10 個以上,優先用 /batch/distill —— 參見 Batch Job Lifecycle

官方 Go SDK 開發中 —— 敬請期待。