Skip to content

Go Examples

Complete Go examples for using the SubX API.

Basic Client

package main

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

type SubXClient struct {
    APIKey  string
    BaseURL string
    Client  *http.Client
}

func NewSubXClient(apiKey string) *SubXClient {
    return &SubXClient{
        APIKey:  apiKey,
        BaseURL: "https://subx-api.duckdns.org",
        Client:  &http.Client{},
    }
}

func (c *SubXClient) Search(params map[string]string) (map[string]interface{}, error) {
    u, _ := url.Parse(c.BaseURL + "/api/subtitles/search")
    q := u.Query()
    for k, v := range params {
        q.Set(k, v)
    }
    u.RawQuery = q.Encode()

    req, _ := http.NewRequest("GET", u.String(), nil)
    req.Header.Set("Authorization", "Bearer "+c.APIKey)

    resp, err := c.Client.Do(req)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    return result, nil
}

func (c *SubXClient) Download(subtitleID, outputPath string) error {
    url := fmt.Sprintf("%s/api/subtitles/%s/download", c.BaseURL, subtitleID)

    req, _ := http.NewRequest("GET", url, nil)
    req.Header.Set("Authorization", "Bearer "+c.APIKey)

    resp, err := c.Client.Do(req)
    if err != nil {
        return err
    }
    defer resp.Body.Close()

    file, err := os.Create(outputPath)
    if err != nil {
        return err
    }
    defer file.Close()

    _, err = io.Copy(file, resp.Body)
    return err
}

func main() {
    client := NewSubXClient(os.Getenv("SUBX_API_KEY"))

    // Search
    results, _ := client.Search(map[string]string{
        "title": "Dexter",
        "limit": "10",
    })

    fmt.Printf("Found %v subtitles\n", results["total"])

    // Download first result
    if items, ok := results["items"].([]interface{}); ok && len(items) > 0 {
        firstItem := items[0].(map[string]interface{})
        subtitleID := firstItem["id"].(string)

        err := client.Download(subtitleID, "subtitle.srt")
        if err == nil {
            fmt.Println("Downloaded successfully!")
        }
    }
}

See the Quickstart Guide for more examples.