ipoalerts Logoipoalerts
Quick Start Examples

Go Examples

Quick start examples for integrating with the API using Go

This page provides practical quick start examples for integrating with the API using Go.

Basic Client

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "time"
)

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

type IPOResponse struct {
    Meta struct {
        Count      int `json:"count"`
        CountOnPage int `json:"countOnPage"`
        TotalPages  int `json:"totalPages"`
        Page        int `json:"page"`
        Limit       int `json:"limit"`
    } `json:"meta"`
    IPOs []IPO `json:"ipos"`
}

type IPO struct {
    ID          string    `json:"id"`
    Name        string    `json:"name"`
    Symbol      string    `json:"symbol"`
    Slug        string    `json:"slug"`
    Type        string    `json:"type"`
    StartDate   string    `json:"startDate"`
    EndDate     string    `json:"endDate"`
    ListingDate string    `json:"listingDate"`
    PriceRange  string    `json:"priceRange"`
    ListingGain string    `json:"listingGain"`
    Status      string    `json:"status"`
    IssueSize   string    `json:"issueSize"`
    MinQty      int       `json:"minQty"`
    MinAmount   int       `json:"minAmount"`
    Logo        string    `json:"logo"`
    About       string    `json:"about"`
    Strengths   []string  `json:"strengths"`
    Risks       []string  `json:"risks"`
    Schedule    []ScheduleItem `json:"schedule"`
}

type ScheduleItem struct {
    Event string `json:"event"`
    Date  string `json:"date"`
}

type IPODetailResponse struct {
    IPO IPO `json:"ipo"`
}

func NewIPOAlertsClient(apiKey string) *IPOAlertsClient {
    return &IPOAlertsClient{
        APIKey:  apiKey,
        BaseURL: "https://api.ipoalerts.in",
        Client: &http.Client{
            Timeout: 30 * time.Second,
        },
    }
}

func (c *IPOAlertsClient) makeRequest(endpoint string, method string, body []byte) (*http.Response, error) {
    var reqBody io.Reader
    if body != nil {
        reqBody = bytes.NewBuffer(body)
    }

    req, err := http.NewRequest(method, c.BaseURL+endpoint, reqBody)
    if err != nil {
        return nil, err
    }

    req.Header.Set("x-api-key", c.APIKey)
    req.Header.Set("Content-Type", "application/json")

    return c.Client.Do(req)
}

func (c *IPOAlertsClient) GetIPOs(status, ipotype string, page, limit int) (*IPOResponse, error) {
    endpoint := fmt.Sprintf("/ipos?status=%s&type=%s&page=%d&limit=%d", status, ipotype, page, limit)
    
    resp, err := c.makeRequest(endpoint, "GET", nil)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode >= 400 {
        return nil, fmt.Errorf("HTTP error: %d", resp.StatusCode)
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    var result IPOResponse
    err = json.Unmarshal(body, &result)
    if err != nil {
        return nil, err
    }

    return &result, nil
}

func (c *IPOAlertsClient) GetIPO(identifier string) (*IPO, error) {
    endpoint := "/ipos/" + identifier
    
    resp, err := c.makeRequest(endpoint, "GET", nil)
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    if resp.StatusCode >= 400 {
        return nil, fmt.Errorf("HTTP error: %d", resp.StatusCode)
    }

    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, err
    }

    var result IPODetailResponse
    err = json.Unmarshal(body, &result)
    if err != nil {
        return nil, err
    }

    return &result.IPO, nil
}

// Usage
func main() {
    client := NewIPOAlertsClient("YOUR_API_KEY")

    // Get upcoming IPOs
    ipos, err := client.GetIPOs("upcoming", "EQ", 1, 10)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    fmt.Printf("Found %d upcoming equity IPOs\n", ipos.Meta.Count)
    for _, ipo := range ipos.IPOs {
        fmt.Printf("%s (%s) - %s\n", ipo.Name, ipo.Symbol, ipo.PriceRange)
    }

    // Get specific IPO
    ipo, err := client.GetIPO("example-company-limited")
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    fmt.Printf("IPO Details: %s\n", ipo.Name)
}

Advanced Client with Rate Limiting and Caching

package main

import (
    "sync"
    "time"
)

type RateLimitedIPOAlertsClient struct {
    *IPOAlertsClient
    rateLimiter chan struct{}
    cache       map[string]CacheEntry
    cacheMutex  sync.RWMutex
    cacheTTL    time.Duration
}

type CacheEntry struct {
    Data      interface{}
    ExpiresAt time.Time
}

func NewRateLimitedIPOAlertsClient(apiKey string, requestsPerMinute int) *RateLimitedIPOAlertsClient {
    client := &RateLimitedIPOAlertsClient{
        IPOAlertsClient: NewIPOAlertsClient(apiKey),
        rateLimiter:     make(chan struct{}, requestsPerMinute),
        cache:           make(map[string]CacheEntry),
        cacheTTL:        5 * time.Minute,
    }
    
    // Fill the rate limiter
    for i := 0; i < requestsPerMinute; i++ {
        client.rateLimiter <- struct{}{}
    }
    
    // Start rate limiter refill goroutine
    go client.refillRateLimiter(requestsPerMinute)
    
    return client
}

func (c *RateLimitedIPOAlertsClient) refillRateLimiter(requestsPerMinute int) {
    ticker := time.NewTicker(time.Minute / time.Duration(requestsPerMinute))
    defer ticker.Stop()
    
    for range ticker.C {
        select {
        case c.rateLimiter <- struct{}{}:
        default:
        }
    }
}

func (c *RateLimitedIPOAlertsClient) waitForRateLimit() {
    <-c.rateLimiter
}

func (c *RateLimitedIPOAlertsClient) getCacheKey(endpoint string, params map[string]interface{}) string {
    key := endpoint
    for k, v := range params {
        key += fmt.Sprintf("_%s_%v", k, v)
    }
    return key
}

func (c *RateLimitedIPOAlertsClient) getFromCache(key string) (interface{}, bool) {
    c.cacheMutex.RLock()
    defer c.cacheMutex.RUnlock()
    
    entry, exists := c.cache[key]
    if !exists || time.Now().After(entry.ExpiresAt) {
        return nil, false
    }
    
    return entry.Data, true
}

func (c *RateLimitedIPOAlertsClient) setCache(key string, data interface{}) {
    c.cacheMutex.Lock()
    defer c.cacheMutex.Unlock()
    
    c.cache[key] = CacheEntry{
        Data:      data,
        ExpiresAt: time.Now().Add(c.cacheTTL),
    }
}

func (c *RateLimitedIPOAlertsClient) GetIPOsWithCache(status, ipotype string, page, limit int) (*IPOResponse, error) {
    params := map[string]interface{}{
        "status": status,
        "type":   ipotype,
        "page":   page,
        "limit":  limit,
    }
    
    cacheKey := c.getCacheKey("/ipos", params)
    
    if cached, exists := c.getFromCache(cacheKey); exists {
        fmt.Println("Returning cached data")
        return cached.(*IPOResponse), nil
    }
    
    c.waitForRateLimit()
    
    result, err := c.GetIPOs(status, ipotype, page, limit)
    if err != nil {
        return nil, err
    }
    
    c.setCache(cacheKey, result)
    return result, nil
}

func (c *RateLimitedIPOAlertsClient) GetIPOWithCache(identifier string) (*IPO, error) {
    params := map[string]interface{}{
        "identifier": identifier,
    }
    
    cacheKey := c.getCacheKey("/ipos/"+identifier, params)
    
    if cached, exists := c.getFromCache(cacheKey); exists {
        fmt.Println("Returning cached IPO data")
        return cached.(*IPO), nil
    }
    
    c.waitForRateLimit()
    
    result, err := c.GetIPO(identifier)
    if err != nil {
        return nil, err
    }
    
    c.setCache(cacheKey, result)
    return result, nil
}

// Usage
func main() {
    client := NewRateLimitedIPOAlertsClient("YOUR_API_KEY", 6)

    // First request - will be cached
    ipos1, err := client.GetIPOsWithCache("upcoming", "EQ", 1, 10)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    // Second request - will return cached data
    ipos2, err := client.GetIPOsWithCache("upcoming", "EQ", 1, 10)
    if err != nil {
        fmt.Printf("Error: %v\n", err)
        return
    }

    fmt.Printf("Found %d upcoming equity IPOs\n", ipos1.Meta.Count)
    fmt.Printf("Cached result: %d upcoming equity IPOs\n", ipos2.Meta.Count)
}

Gin Web Framework Integration

package main

import (
    "net/http"
    "strconv"
    
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/cache"
    "github.com/gin-contrib/cache/persistence"
)

type IPOController struct {
    client *IPOAlertsClient
    cache  persistence.CacheStore
}

func NewIPOController(apiKey string) *IPOController {
    return &IPOController{
        client: NewIPOAlertsClient(apiKey),
        cache:  persistence.NewInMemoryStore(time.Minute * 5),
    }
}

func (ctrl *IPOController) GetIPOs(c *gin.Context) {
    status := c.Query("status")
    ipotype := c.Query("type")
    page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
    limit, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))
    
    cacheKey := fmt.Sprintf("ipos_%s_%s_%d_%d", status, ipotype, page, limit)
    
    var result *IPOResponse
    err := ctrl.cache.Get(cacheKey, &result)
    if err != nil {
        // Cache miss, make API request
        result, err = ctrl.client.GetIPOs(status, ipotype, page, limit)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        
        // Cache the result
        ctrl.cache.Set(cacheKey, result, time.Minute*5)
    }
    
    c.JSON(http.StatusOK, result)
}

func (ctrl *IPOController) GetIPO(c *gin.Context) {
    identifier := c.Param("identifier")
    
    cacheKey := "ipo_" + identifier
    
    var result *IPO
    err := ctrl.cache.Get(cacheKey, &result)
    if err != nil {
        // Cache miss, make API request
        result, err = ctrl.client.GetIPO(identifier)
        if err != nil {
            c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
            return
        }
        
        // Cache the result
        ctrl.cache.Set(cacheKey, result, time.Minute*5)
    }
    
    c.JSON(http.StatusOK, gin.H{"ipo": result})
}

func main() {
    r := gin.Default()
    
    // Initialize controller
    controller := NewIPOController("YOUR_API_KEY")
    
    // Routes
    api := r.Group("/api")
    {
        api.GET("/ipos", controller.GetIPOs)
        api.GET("/ipos/:identifier", controller.GetIPO)
    }
    
    r.Run(":8080")
}