Go
Go SDK
了解如何用 bannerify-go 模組生成圖片和 PDF。
bannerify-go 是 Go 的 Bannerify 用戶端。每個請求都接受 context.Context,並以值的形式回傳錯誤。
安裝
go get github.com/bannerify/bannerify-go
建立用戶端
你需要一組 API 金鑰。請到儀表板的 API Keys 頁面建立,並把它留在伺服器上。
import "github.com/bannerify/bannerify-go"
client := bannerify.NewClient(os.Getenv("BANNERIFY_API_KEY"))
生成圖片
除了 Name 之外,Modification 的每個欄位都是指標。範例用下面的輔助函式來建立指標:
package main
import (
"context"
"fmt"
"os"
"github.com/bannerify/bannerify-go"
)
func ptr[T any](value T) *T { return &value }
func main() {
client := bannerify.NewClient(os.Getenv("BANNERIFY_API_KEY"))
result := client.CreateImage(context.Background(), "tpl_xxx", &bannerify.CreateImageOptions{
Modifications: []bannerify.Modification{
{Name: "headline", Text: ptr("Summer sale")},
},
})
if result.Error != nil {
fmt.Println(result.Error.Message)
return
}
if err := os.WriteFile("banner.png", result.Result, 0o644); err != nil {
fmt.Println(err)
}
}
result.Result 是存放圖片的 []byte。
方法
| 方法 | 回傳 | 用途 |
|---|---|---|
CreateImage |
*Response |
在 Result 中取得圖片的位元組 |
CreatePDF |
*Response |
在 Result 中取得 PDF |
RenderVideo (Beta) |
iter.Seq[RenderVideoEvent] |
渲染影片並追蹤進度 |
RenderAndWaitVideo (Beta) |
string 和 error |
渲染影片並取得它的 MP4 網址 |
CreateVideo (Beta) |
*CreatedVideo 和 error |
不等待就開始影片,並立即取得它的 ID |
GetVideo (Beta) |
*Video 和 error |
依 ID 讀取影片的狀態和 MP4 網址 |
WatchVideo (Beta) |
iter.Seq[RenderVideoEvent] |
依 ID 再次追蹤影片的進度 |
GenerateImageSignedURL |
string 和 error |
建立一個在有人開啟時渲染的連結 |
影片方法請見渲染影片。Go SDK 沒有已儲存圖片的方法,請透過 REST 呼叫建立已儲存的圖片。
處理錯誤
CreateImage 和 CreatePDF 會回傳 *Response。讀取 Result 之前,請先檢查 Error。
type Response struct {
Result []byte
Error *ErrorResponse
}
type ErrorResponse struct {
Code string
Message string
Docs string
}
當 API 回應 200 以外的狀態時,SDK 會回傳代碼 HTTP_ERROR。對 CreateImage 來說,訊息包含狀態和回應內文,也就是 API 回傳的 JSON 錯誤物件。對 CreatePDF 來說,訊息只包含狀態。
SDK 自己還會建立幾種其他錯誤。
| 代碼 | 意義 |
|---|---|
INVALID_FORMAT |
格式不是 png、jpeg 或 webp |
JSON_ERROR |
SDK 無法編碼請求內文 |
REQUEST_ERROR |
SDK 無法建立請求 |
HTTP_ERROR |
請求在 API 回應之前就失敗,或 API 回應了 200 以外的狀態 |
READ_ERROR |
SDK 無法讀取回應內文 |
TIMEOUT_ERROR |
影片串流中斷,且 SDK 無法再次讀取影片 |
當格式不受支援時,GenerateImageSignedURL 會回傳 error。
選項
在 API 金鑰之後,把選項傳給 NewClient。
client := bannerify.NewClient(
os.Getenv("BANNERIFY_API_KEY"),
bannerify.WithTimeout(30*time.Second),
)
| 選項 | 預設值 | 說明 |
|---|---|---|
WithBaseURL(url) |
https://api.bannerify.co/v1 |
API 的基本網址 |
WithTimeout(duration) |
60 秒 | 請求逾時時間 |
WithHTTPClient(client) |
逾時時間為 60 秒的用戶端 | 你自己的 *http.Client。它會取代預設用戶端,所以請在它上面設定逾時時間 |