Golang의 YouTube 스크립트: net/http 및 3개의 Structs

전체 프로그램입니다. 설명은 이후입니다.
package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"os"
"time"
)
type Transcript struct {
VideoID string `json:"videoId"`
Title string `json:"title"`
PubDate string `json:"pubDate"`
Content string `json:"content"`
ContentSize int `json:"contentSize"`
Truncated bool `json:"truncated"`
}
type APIError struct {
Code string `json:"code"`
Message string `json:"message"`
Status int `json:"status"`
RetryAfterSeconds int `json:"retryAfterSeconds"`
}
type envelope struct {
Result *Transcript `json:"result"`
Error *APIError `json:"error"`
}
func main() {
q := url.Values{}
q.Set("url", "https://www.youtube.com/watch?v=dQw4w9WgXcQ")
req, err := http.NewRequest(http.MethodGet,
"https://youtube2text.org/api/transcribe?"+q.Encode(), nil)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
req.Header.Set("x-api-key", os.Getenv("YT2TEXT_KEY"))
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer resp.Body.Close()
var env envelope
if err := json.NewDecoder(resp.Body).Decode(&env); err != nil {
fmt.Fprintln(os.Stderr, "decode:", err)
os.Exit(1)
}
if env.Error != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", env.Error.Code, env.Error.Message)
os.Exit(1)
}
fmt.Println(env.Result.Title)
fmt.Printf("%d chars, truncated=%v\n",
env.Result.ContentSize, env.Result.Truncated)
}
go run main.go, 완료. 타사 모듈이 없습니다. Golang에서 YouTube 스크립트를 얻는 방식이므로 API는 일반 HTTPS이며 JSON을 반환합니다. net/http와 encoding/json이 모든 것을 다룹니다. 이에 대한 공식 Go 라이브러리는 없으며, 저는 그것이 기능이라고 주장할 것입니다.
봉투 트릭
성공 응답은 result 아래에 데이터를 넣습니다. 실패는 error 아래에 구조화된 개체를 넣습니다. 두 포인터 필드가 있는 하나의 struct로 둘 다 디코딩하면 단일 Decode 호출이 모든 응답을 처리합니다. 어느 포인터가 nil이 아닌지는 당신의 대답입니다. 본문을 다시 읽거나 Content-Type을 스니핑하지 않으며, env.Error.Status는 double-check하려면 HTTP 상태와 일치합니다.
스위치 문장의 가치가 있는 코드
APIError.Code는 안정적이므로 메시지 문자열이 아닌 코드에서 분기하세요:
switch env.Error.Code {
case "RATE_LIMIT_EXCEEDED":
wait := time.Duration(env.Error.RetryAfterSeconds) * time.Second
time.Sleep(wait) // then retry the request
case "TRANSCRIPT_UNAVAILABLE":
// video exists but has no caption track — skip permanently
case "VIDEO_NOT_FOUND", "INVALID_URL":
// bad input; log and move on
default:
// UNAUTHORIZED, VALIDATION_ERROR, YOUTUBE_ERROR
}
TRANSCRIPT_UNAVAILABLE은 사람들이 처리하는 것입니다. 스크립트는 YouTube의 캡션 트랙에서 나옵니다. 수동 또는 자동 생성, 영어 선호, 그렇지 않으면 첫 번째 사용 가능한 언어입니다. 비디오가 캡션을 꺼놨으면 가져올 스크립트가 없고 지수 백오프로 재시도하면 캡션이 증가하지 않습니다. 배치 작업에서 영구 건너뛰기로 처리하거나 워커 큐가 좀비로 채워집니다.
매개변수 및 키
총 2개의 쿼리 매개변수. url은 모든 YouTube URL 형태 또는 11자 ID를 가져옵니다. maxChars는 출력 길이를 제한합니다 (150000은 기본값 및 최대값). 스크립트가 LLM을 공급하고 토큰당 비용을 지불할 때 유용하며, 대부분의 Go 사용 사례를 들었습니다. 보통 전체 채널 위의 RAG.
가입 없이 키를 원하면 curl https://youtube2text.org/api/demo-key는 작동하는 것을 반환합니다. 모든 익명 사용자 간에 공유되며 IP당 월 5개 비디오로 제한되므로 엄격히 시도용입니다. yt-dlp 자막 파일로 외치는 것과 비교하면 yt-dlp 자막 vs API 비교를 작성했습니다. 스택의 일부가 Node이면 JavaScript에서 동일한 호출은 더 짧습니다.
실제 사용의 경우 youtube2text.org/app/keys에서 Google으로 로그인하세요. 카드 없음, 전화 없음, 월 5개 비디오의 무료 계층, $5.99 50개부터 $19.99 무제한의 유료 계층입니다. 위의 Go 코드는 변경되지 않습니다. 환경 변수만 변경됩니다.