Files
caddybun/porkbun.go
2026-02-20 09:55:36 -05:00

65 lines
1.5 KiB
Go

package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type porkbunRequest struct {
APIKey string `json:"apikey"`
SecretAPIKey string `json:"secretapikey"`
Name string `json:"name"`
Type string `json:"type"`
Content string `json:"content"`
TTL string `json:"ttl"`
}
type porkbunResponse struct {
Status string `json:"status"`
ID json.Number `json:"id"`
Message string `json:"message"`
}
func CreateDNSRecord(cfg *Config, subdomain string) (string, error) {
url := fmt.Sprintf("https://api.porkbun.com/api/json/v3/dns/create/%s", cfg.Domain)
body := porkbunRequest{
APIKey: cfg.PorkbunAPIKey,
SecretAPIKey: cfg.PorkbunSecretKey,
Name: subdomain,
Type: "CNAME",
Content: cfg.Domain,
TTL: "600",
}
payload, err := json.Marshal(body)
if err != nil {
return "", fmt.Errorf("marshaling request: %w", err)
}
resp, err := http.Post(url, "application/json", bytes.NewReader(payload))
if err != nil {
return "", fmt.Errorf("sending request: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("reading response: %w", err)
}
var result porkbunResponse
if err := json.Unmarshal(respBody, &result); err != nil {
return "", fmt.Errorf("parsing response: %w", err)
}
if result.Status != "SUCCESS" {
return "", fmt.Errorf("porkbun API error: %s", result.Message)
}
return result.ID.String(), nil
}