Skip to content

Go SDK

Official Go SDK for QR Code API.

Installation

bash
go get github.com/qrcodeapi/qrcodeapi-go

Quick Start

go
package main

import (
    "os"
    "github.com/qrcodeapi/qrcodeapi-go"
)

func main() {
    client := qrcodeapi.NewClient(os.Getenv("QRCODE_API_KEY"))
    
    // Generate a QR code
    qr, err := client.Generate(&qrcodeapi.GenerateOptions{
        Data:  "https://example.com",
        Size:  400,
        Color: "22c55e",
    })
    if err != nil {
        panic(err)
    }
    
    // Save to file
    os.WriteFile("qr.png", qr, 0644)
}

Configuration

go
client := qrcodeapi.NewClient(
    os.Getenv("QRCODE_API_KEY"),
    qrcodeapi.WithBaseURL("https://www.qrcodeapi.io/api"),
    qrcodeapi.WithTimeout(30 * time.Second),
    qrcodeapi.WithRetry(3, time.Second),
)

API Reference

Generate()

Generate a QR code image.

go
type GenerateOptions struct {
    Data            string // Required
    Size            int    // 50-2000 (default: 300)
    Format          string // "png" or "svg" (default: "png")
    Color           string // Hex without # (default: "000000")
    Background      string // Hex without # (default: "ffffff")
    ErrorCorrection string // "L", "M", "Q", or "H" (default: "M")
    Margin          int    // 0-10 (default: 4)
    Logo            string // Logo URL (Pro plan)
    LogoSize        int    // 10-40 as % (default: 20)
}

qr, err := client.Generate(&GenerateOptions{
    Data:  "https://example.com",
    Size:  400,
    Color: "4f46e5",
})

Returns []byte (the image data).

Create a dynamic link.

go
type CreateLinkOptions struct {
    Name      string
    TargetURL string
}

type DynamicLink struct {
    ID        string    `json:"id"`
    Name      string    `json:"name"`
    ShortCode string    `json:"shortCode"`
    TargetURL string    `json:"targetUrl"`
    ScanCount int       `json:"scanCount"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`
}

link, err := client.Links.Create(&CreateLinkOptions{
    Name:      "My Campaign",
    TargetURL: "https://example.com",
})

Get all dynamic links.

go
links, err := client.Links.List()
for _, link := range links {
    fmt.Printf("%s: %s (%d scans)\n", link.Name, link.ShortCode, link.ScanCount)
}

Get a single link by ID.

go
link, err := client.Links.Get("link-id")

Update a dynamic link.

go
type UpdateLinkOptions struct {
    Name      string
    TargetURL string
}

link, err := client.Links.Update("link-id", &UpdateLinkOptions{
    TargetURL: "https://new-url.com",
})

Delete a dynamic link.

go
err := client.Links.Delete("link-id")

Analytics.Get()

Get scan analytics for a dynamic link.

go
type AnalyticsOptions struct {
    LinkID    string
    StartDate time.Time
    EndDate   time.Time
}

type Analytics struct {
    TotalScans   int `json:"totalScans"`
    UniqueScans  int `json:"uniqueScans"`
    ByDay       []DayScan    `json:"scansByDay"`
    ByCountry   []CountryScan `json:"scansByCountry"`
    ByDevice    []DeviceScan  `json:"scansByDevice"`
}

analytics, err := client.Analytics.Get(&AnalyticsOptions{
    LinkID:    "link-id",
    StartDate: time.Now().AddDate(0, 0, -30),
    EndDate:   time.Now(),
})

fmt.Printf("Total scans: %d\n", analytics.TotalScans)

Batch.Generate()

Generate multiple QR codes (Pro plan).

go
type BatchItem struct {
    Data     string
    Filename string
    Size     int
    Color    string
}

type BatchOptions struct {
    Items    []BatchItem
    Defaults *GenerateOptions
}

zipData, err := client.Batch.Generate(&BatchOptions{
    Items: []BatchItem{
        {Data: "https://example.com/1", Filename: "qr1.png"},
        {Data: "https://example.com/2", Filename: "qr2.png"},
    },
    Defaults: &GenerateOptions{
        Size:  400,
        Color: "4f46e5",
    },
})

// Save ZIP file
os.WriteFile("qrcodes.zip", zipData, 0644)

Complete Example

go
package main

import (
    "fmt"
    "os"
    
    "github.com/qrcodeapi/qrcodeapi-go"
)

func main() {
    client := qrcodeapi.NewClient(os.Getenv("QRCODE_API_KEY"))
    
    // 1. Create a dynamic link
    link, err := client.Links.Create(&qrcodeapi.CreateLinkOptions{
        Name:      "Product Launch",
        TargetURL: "https://company.com/launch",
    })
    if err != nil {
        panic(err)
    }
    fmt.Printf("Created link: %s\n", link.ShortCode)
    
    // 2. Generate QR code
    qr, err := client.Generate(&qrcodeapi.GenerateOptions{
        Data:            fmt.Sprintf("https://www.qrcodeapi.io/r/%s", link.ShortCode),
        Size:            500,
        Color:           "1e40af",
        ErrorCorrection: "H",
    })
    if err != nil {
        panic(err)
    }
    
    os.WriteFile("launch-qr.png", qr, 0644)
    fmt.Println("Saved launch-qr.png")
    
    // 3. Update target URL
    _, err = client.Links.Update(link.ID, &qrcodeapi.UpdateLinkOptions{
        TargetURL: "https://company.com/launch-v2",
    })
    if err != nil {
        panic(err)
    }
    fmt.Println("Updated link target")
    
    // 4. Check analytics
    analytics, err := client.Analytics.Get(&qrcodeapi.AnalyticsOptions{
        LinkID: link.ID,
    })
    if err != nil {
        panic(err)
    }
    fmt.Printf("Total scans: %d\n", analytics.TotalScans)
}

Error Handling

go
import (
    "errors"
    "github.com/qrcodeapi/qrcodeapi-go"
)

qr, err := client.Generate(&qrcodeapi.GenerateOptions{
    Data: "test",
})

if err != nil {
    var apiErr *qrcodeapi.APIError
    if errors.As(err, &apiErr) {
        switch apiErr.StatusCode {
        case 401:
            fmt.Println("Invalid API key")
        case 429:
            fmt.Printf("Rate limited. Retry after %d seconds\n", apiErr.RetryAfter)
        default:
            fmt.Printf("API error: %s (status: %d)\n", apiErr.Message, apiErr.StatusCode)
        }
    } else {
        fmt.Printf("Error: %v\n", err)
    }
}

Concurrent Generation

go
import (
    "sync"
    "github.com/qrcodeapi/qrcodeapi-go"
)

func generateMany(client *qrcodeapi.Client, urls []string) [][]byte {
    var wg sync.WaitGroup
    results := make([][]byte, len(urls))
    
    for i, url := range urls {
        wg.Add(1)
        go func(i int, url string) {
            defer wg.Done()
            qr, err := client.Generate(&qrcodeapi.GenerateOptions{
                Data: url,
            })
            if err != nil {
                fmt.Printf("Error generating QR for %s: %v\n", url, err)
                return
            }
            results[i] = qr
        }(i, url)
    }
    
    wg.Wait()
    return results
}

HTTP Handler

go
package main

import (
    "net/http"
    "os"
    "strconv"
    
    "github.com/qrcodeapi/qrcodeapi-go"
)

var client = qrcodeapi.NewClient(os.Getenv("QRCODE_API_KEY"))

func qrHandler(w http.ResponseWriter, r *http.Request) {
    data := r.URL.Query().Get("data")
    if data == "" {
        http.Error(w, "data required", http.StatusBadRequest)
        return
    }
    
    size := 300
    if s := r.URL.Query().Get("size"); s != "" {
        size, _ = strconv.Atoi(s)
    }
    
    qr, err := client.Generate(&qrcodeapi.GenerateOptions{
        Data: data,
        Size: size,
    })
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    
    w.Header().Set("Content-Type", "image/png")
    w.Write(qr)
}

func main() {
    http.HandleFunc("/qr", qrHandler)
    http.ListenAndServe(":8080", nil)
}

Gin Integration

go
package main

import (
    "os"
    "strconv"
    
    "github.com/gin-gonic/gin"
    "github.com/qrcodeapi/qrcodeapi-go"
)

var client = qrcodeapi.NewClient(os.Getenv("QRCODE_API_KEY"))

func main() {
    r := gin.Default()
    
    r.GET("/qr", func(c *gin.Context) {
        data := c.Query("data")
        if data == "" {
            c.JSON(400, gin.H{"error": "data required"})
            return
        }
        
        size := 300
        if s := c.Query("size"); s != "" {
            size, _ = strconv.Atoi(s)
        }
        
        qr, err := client.Generate(&qrcodeapi.GenerateOptions{
            Data: data,
            Size: size,
        })
        if err != nil {
            c.JSON(500, gin.H{"error": err.Error()})
            return
        }
        
        c.Data(200, "image/png", qr)
    })
    
    r.Run(":8080")
}