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)Tips
- 1 つの
*http.Clientを Goroutine 間で使い回すこと —— スレッドセーフで接続もプールされます - レスポンス Body は必ず閉じる(
defer resp.Body.Close())—— さもないと FD がリークします - 10 件以上の URL を扱うなら
/batch/distillのほうが望ましいです —— Batch Job Lifecycle を参照
公式 Go SDK は開発中です —— もう少しお待ちください。