Digito

Go

Consulta sobres con net/http y decodifica la paginación.

Este ejemplo utiliza net/http para consultar sobres y encoding/json para leer la respuesta. Utiliza únicamente la biblioteca estándar de Go.

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "time"
)

type envelopePage struct {
    Data []struct {
        ID string `json:"id"`
        Title string `json:"title"`
        Status string `json:"status"`
    } `json:"data"`
    CurrentPage int `json:"currentPage"`
    TotalPages int `json:"totalPages"`
}

func run() error {
    token := os.Getenv("DIGITO_API_TOKEN")
    if token == "" {
        return fmt.Errorf("falta DIGITO_API_TOKEN")
    }

    request, err := http.NewRequest(http.MethodGet,
        "https://business.digito.do/api/v2/envelope?type=DOCUMENT&page=1&perPage=20", nil)
    if err != nil {
        return err
    }
    request.Header.Set("Authorization", token)

    client := &http.Client{Timeout: 15 * time.Second}
    response, err := client.Do(request)
    if err != nil {
        return err
    }
    defer response.Body.Close()

    if response.StatusCode < 200 || response.StatusCode >= 300 {
        return fmt.Errorf("la consulta falló: HTTP %d", response.StatusCode)
    }

    var result envelopePage
    if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
        return err
    }

    for _, envelope := range result.Data {
        fmt.Println(envelope.ID, envelope.Title, envelope.Status)
    }

    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

La estructura local incluye sólo los campos utilizados. Para procesar más páginas, incrementa el parámetro page y revisa currentPage y totalPages.

Mantén la clave en el servidor, conserva un tiempo de espera y cierra el cuerpo de las respuestas. No descargues un PDF con el decodificador JSON; almacena el cuerpo como bytes después de comprobar el estado y el tipo de contenido.