Files
routewatch/cmd/asinfo-gen/main.go
T
sneak c152ddd5f4
check / check (push) Waiting to run
Re-vendor the shared files from sneak/prompts at dd4027b (closes #52)
Takes .golangci.yml, .dockerignore, .gitignore, .editorconfig, the
workflow and REPO_POLICIES.md from sneak/prompts dd4027b, keeping this
repository's own entries after the shared content. Lint (golangci-lint
v2.14.0) and test become Dockerfile phases that script/lint and
script/test build alone and uncached; the image build depends on both,
and script/cibuild bootstraps, runs script/check, then builds the image.
The agent guidance file moves to AGENTS.md. The Go code is fixed for
what the new configuration finds; reads that iterate rows now also
report an iteration error.

Model: opus-5-5
2026-10-14 13:57:50 +00:00

113 lines
2.3 KiB
Go

// Package main generates the embedded AS info data for the asinfo package
package main
import (
"context"
"encoding/csv"
"encoding/json"
"errors"
"io"
"log"
"net/http"
"os"
"strconv"
"strings"
)
const asCsvURL = "https://github.com/ipverse/asn-info/raw/refs/heads/master/as.csv"
// ASInfo represents information about an Autonomous System
type ASInfo struct {
ASN int `json:"asn"`
Handle string `json:"handle"`
Description string `json:"description"`
}
func main() {
// Configure logger to write to stderr
log.SetOutput(os.Stderr)
// Fetch the CSV data
log.Println("Fetching AS CSV data...")
req, err := http.NewRequestWithContext(
context.Background(), http.MethodGet, asCsvURL, nil)
if err != nil {
log.Fatalf("Failed to fetch CSV: %v", err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Failed to fetch CSV: %v", err)
}
if resp.StatusCode != http.StatusOK {
log.Fatalf("Failed to fetch CSV: HTTP %d", resp.StatusCode)
}
// Parse CSV
reader := csv.NewReader(resp.Body)
// Read header
header, err := reader.Read()
if err != nil {
log.Fatalf("Failed to read CSV header: %v", err)
}
if len(header) != 3 || header[0] != "asn" || header[1] != "handle" ||
header[2] != "description" {
log.Fatalf("Unexpected CSV header: %v", header)
}
// Read all records
var asInfos []ASInfo
for {
record, err := reader.Read()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
log.Printf("Error reading CSV record: %v", err)
continue
}
const expectedFields = 3
if len(record) != expectedFields {
log.Printf("Skipping invalid record: %v", record)
continue
}
asn, err := strconv.Atoi(record[0])
if err != nil {
log.Printf("Invalid ASN %q: %v", record[0], err)
continue
}
asInfos = append(asInfos, ASInfo{
ASN: asn,
Handle: strings.TrimSpace(record[1]),
Description: strings.TrimSpace(record[2]),
})
}
// Closed here rather than deferred: log.Fatalf exits without running
// deferred calls.
_ = resp.Body.Close()
log.Printf("Parsed %d AS records", len(asInfos))
// Convert to JSON and output to stdout
encoder := json.NewEncoder(os.Stdout)
encoder.SetIndent("", "\t")
err = encoder.Encode(asInfos)
if err != nil {
log.Fatalf("Failed to encode JSON: %v", err)
}
}