# A small Go client for the astrology API: timeouts, typed errors, time zones

> Go needs no SDK for this - `net/http` and `encoding/json` cover it. Below is a 60-line client that unwraps the response envelope into your own types, turns API errors into a typed `error`, and a choghadiya example that shows why `time.Time` values need `.In(...)` before you print them.

Source: https://astronode.dev/integrations/go · Updated: 2026-12-01

**How this page was verified:** Executed as written with `go run` against the in-memory API: the three windows and the validation error below are that program's output.

## The client

`astronode/client.go`:

```go
type Client struct {
	BaseURL string
	APIKey  string
	HTTP    *http.Client
}

func NewClient() *Client {
	base := os.Getenv("ASTRONODE_BASE_URL")
	if base == "" {
		base = "https://api.astronode.dev"
	}
	return &Client{
		BaseURL: base,
		APIKey:  os.Getenv("ASTRONODE_API_KEY"),
		HTTP:    &http.Client{Timeout: 15 * time.Second}, // http.DefaultClient never times out
	}
}

type APIError struct {
	Status     int
	Code       string `json:"code"`
	Message    string `json:"message"`
	RetryAfter time.Duration
}

func (e *APIError) Error() string { return fmt.Sprintf("astronode %d %s: %s", e.Status, e.Code, e.Message) }

// Post sends body to path and decodes the envelope's "data" into out.
func (c *Client) Post(ctx context.Context, path string, body, out any) error {
	buf, err := json.Marshal(body)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+path, bytes.NewReader(buf))
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+c.APIKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := c.HTTP.Do(req)
	if err != nil {
		return err
	}
	defer res.Body.Close()

	var env struct {
		Data  json.RawMessage `json:"data"`
		Error *APIError       `json:"error"`
	}
	if err := json.NewDecoder(res.Body).Decode(&env); err != nil {
		return fmt.Errorf("astronode %d: %w", res.StatusCode, err)
	}
	if env.Error != nil {
		env.Error.Status = res.StatusCode
		if s, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil {
			env.Error.RetryAfter = time.Duration(s) * time.Second
		}
		return env.Error
	}
	return json.Unmarshal(env.Data, out)
}
```

Callers can `errors.As(err, &apiErr)` and branch on `apiErr.Code` (`VALIDATION_ERROR`, `RATE_LIMITED`, `QUOTA_EXCEEDED`, ...). `RetryAfter` is filled from the header the API sends with every `429`, so a worker can sleep exactly that long instead of guessing.

## Choghadiya windows, typed

```go
type Window struct {
	Name    string    `json:"name"`
	Start   time.Time `json:"start"`
	End     time.Time `json:"end"`
	Lord    string    `json:"lord"`
	Quality string    `json:"quality"`
}

type Choghadiya struct {
	Date  string   `json:"date"`
	Day   []Window `json:"day"`
	Night []Window `json:"night"`
}

type DayInput struct {
	Date            string  `json:"date"`
	TzOffsetMinutes int     `json:"tz_offset_minutes"`
	Lat             float64 `json:"lat"`
	Lng             float64 `json:"lng"`
}

func main() {
	c := NewClient()
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	var ch Choghadiya
	in := DayInput{Date: "2026-12-01", TzOffsetMinutes: 330, Lat: 19.076, Lng: 72.8777}
	if err := c.Post(ctx, "/v1/muhurta/choghadiya", in, &ch); err != nil {
		fmt.Println("error:", err)
		os.Exit(1)
	}
	ist := time.FixedZone("IST", in.TzOffsetMinutes*60)
	for _, w := range ch.Day {
		if w.Quality == "auspicious" {
			fmt.Printf("%-6s %s-%s (%s)\n", w.Name, w.Start.In(ist).Format("15:04"), w.End.In(ist).Format("15:04"), w.Lord)
		}
	}
}
```

Output for Mumbai, Tuesday 1 December 2026:

```text
Labh   11:04-12:27 (Mercury)
Amrit  12:27-13:50 (Moon)
Shubh  15:13-16:36 (Jupiter)
```

The API's ISO timestamps decode straight into `time.Time`. Each day has eight day and eight night windows from sunrise to sunrise; the first day window was Rog from 06:55, Tuesday's traditional starting point. Leaving out `tz_offset_minutes` made the same program print `astronode 400 VALIDATION_ERROR: Request validation failed`.

## The mistakes that bite first

- **`http.DefaultClient` / `http.Post`.** Neither has a timeout, so one stuck connection holds a goroutine (and whatever request is waiting on it) forever. Always construct a client with `Timeout`, and pass a `context` for per-call deadlines.
- **Printing `time.Time` without `.In(...)`.** The values are UTC instants. `w.Start.Format("15:04")` on a server running in UTC prints Labh at 05:34, not 11:04. Convert to the location's offset with `time.FixedZone` (from the same `tz_offset_minutes` you sent) - not `time.Local`, which is the server's zone.
- **Decoding into `map[string]any`.** It works, but every number becomes `float64` and every typo becomes a silent nil. Structs with `json` tags fail loudly when the shape is not what you expected.

## Questions

**Which AstroNode endpoints does the Go example call?**

1 endpoint: Choghadiya (`POST /v1/muhurta/choghadiya`).

**Was the Go code on this page actually run?**

Executed as written with `go run` against the in-memory API: the three windows and the validation error below are that program's output.

## Endpoints

- [`POST /v1/muhurta/choghadiya`](https://astronode.dev/capabilities/vedic/muhurta-choghadiya) - Choghadiya API
