# Go

Source: https://prontaro.com/docs/languages/go/

Use your dedicated static IPv4 in Go for HTTPS APIs, SOCKS5, and direct TCP sockets with a shared http.Client and minimal external dependencies.

Go’s standard `net/http` handles `https://`, `http://`, and `socks5h://` natively through `http.ProxyURL`; reach for `golang.org/x/net/proxy` only when dialing databases or custom TCP protocols directly.

| Use case | Package | Supported schemes |
| --- | --- | --- |
| HTTP/HTTPS APIs | Standard `net/http` | `https://`, `http://`, `socks5h://` |
| Direct TCP / DB drivers | `golang.org/x/net/proxy` | `socks5h://` |
| HTTPS APIs without proxy config | Standard `net/http` + Relay | `https://*.prontaro.run` |

## Step 1. Get your proxy URL

1. Open **IP addresses** in your Prontaro dashboard ([my.prontaro.com/ips](https://my.prontaro.com/ips)) and select your IPv4.
2. Copy the `HTTPS` (`:443`) or `SOCKS5` (`:1080`) URL under **Proxy credentials**.

IP addresses Proxy credentials [Open in dashboard](https://my.prontaro.com/ips)

Export the proxy string to `PRONTARO_PROXY_URL`:

```bash
export PRONTARO_PROXY_URL="https://user:pass@<entry>.prontaro.io:443"
```

## `net/http`: `http.Transport` with `http.ProxyURL`

Clone `http.DefaultTransport` to keep Go’s dial, TLS, and HTTP/2 defaults, then set `Proxy`. Always check both transport errors and `resp.StatusCode` — `client.Do` returns `err == nil` on `4xx`/`5xx` responses from the target API:

```go
// main.go
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

func newProxyClient(rawURL string) (*http.Client, error) {
	if rawURL == "" {
		return nil, fmt.Errorf("PRONTARO_PROXY_URL is empty")
	}
	u, err := url.Parse(rawURL)
	if err != nil {
		return nil, fmt.Errorf("parse proxy URL: %w", err)
	}
	if u.Scheme == "" || u.Host == "" {
		return nil, fmt.Errorf("proxy URL must include scheme and host")
	}

	transport := http.DefaultTransport.(*http.Transport).Clone()
	transport.Proxy = http.ProxyURL(u)
	transport.MaxIdleConns = 50
	transport.MaxIdleConnsPerHost = 20

	return &http.Client{
		Transport: transport,
		Timeout:   15 * time.Second,
	}, nil
}

func checkOutboundIP(ctx context.Context, client *http.Client) (string, error) {
	req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.ipify.org", nil)
	if err != nil {
		return "", fmt.Errorf("build request: %w", err)
	}

	resp, err := client.Do(req)
	if err != nil {
		return "", fmt.Errorf("do request: %w", err)
	}
	defer resp.Body.Close()

	body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
	if err != nil {
		return "", fmt.Errorf("read body: %w", err)
	}
	if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
		return "", fmt.Errorf("unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
	}

	return strings.TrimSpace(string(body)), nil
}

func main() {
	client, err := newProxyClient(os.Getenv("PRONTARO_PROXY_URL"))
	if err != nil {
		log.Fatalf("init client: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	ip, err := checkOutboundIP(ctx, client)
	if err != nil {
		log.Fatalf("egress check failed: %v", err)
	}
	fmt.Println(ip)
}
```

Verify your outbound IP (the same program works with `socks5h://user:pass@<entry>.prontaro.io:1080`):

```
 
203.0.113.10
```

Once this succeeds, you can restrict allowed destinations in the dashboard (**IP addresses → Proxy credentials → Access**).

## `golang.org/x/net/proxy` for `socks5h://` and direct TCP

For direct TCP protocols (PostgreSQL, Redis, SSH, or custom protocols), use `golang.org/x/net/proxy`. `proxy.SOCKS5` always sends the hostname to the Prontaro node for remote DNS resolution, so domain rules in your **To** allowlist match cleanly:

```bash
go get golang.org/x/net/proxy
```

```go
// dial_socks.go
package egress

import (
	"context"
	"fmt"
	"net"
	"net/url"

	"golang.org/x/net/proxy"
)

func NewSOCKS5Dialer(rawURL string) (func(ctx context.Context, network, addr string) (net.Conn, error), error) {
	u, err := url.Parse(rawURL)
	if err != nil {
		return nil, fmt.Errorf("parse socks URL: %w", err)
	}
	if u.Scheme != "socks5h" && u.Scheme != "socks5" {
		return nil, fmt.Errorf("expected socks5h:// scheme, got %q", u.Scheme)
	}

	var auth *proxy.Auth
	if u.User != nil {
		pass, _ := u.User.Password()
		auth = &proxy.Auth{
			User:     u.User.Username(),
			Password: pass,
		}
	}

	dialer, err := proxy.SOCKS5("tcp", u.Host, auth, proxy.Direct)
	if err != nil {
		return nil, fmt.Errorf("create socks5 dialer: %w", err)
	}
	ctxDialer, ok := dialer.(proxy.ContextDialer)
	if !ok {
		return nil, fmt.Errorf("socks5 dialer does not implement ContextDialer")
	}

	return ctxDialer.DialContext, nil
}
```

Pass the returned `DialContext` directly into `pgx.ConnConfig.DialFunc`, `redis.Options.Dialer`, or call it manually for `db.example.com:5432`.

## Reusing `http.Client`

`http.Client` and `http.Transport` are safe for concurrent use across goroutines. Construct one client at startup and inject it wherever partner API calls happen.

> **Drain and close resp.Body on every request**
>
> Go only returns a TCP/TLS connection to the keep-alive pool if you read `resp.Body` to `EOF` and close it (`io.Copy(io.Discard, resp.Body)` + `resp.Body.Close()`). Skipping this forces a fresh proxy tunnel per call and burns through [concurrent connection limits](https://prontaro.com/docs/billing/limits.md).

## Common Go issues

- **Constructing `&http.Transport{}` from scratch.** Omitting `.Clone()` drops `DialContext` and `TLSHandshakeTimeout`, leaving stalled connections hung indefinitely.
- **`http.ProxyFromEnvironment` caches env vars once.** `DefaultTransport` reads `HTTPS_PROXY`/`NO_PROXY` via `sync.Once`, so calling `os.Setenv` after the first request has no effect. Prefer explicit `http.ProxyURL`.
- **Ignoring `resp.StatusCode`.** Upstream `403`/`500` responses return `err == nil`, while proxy-level `CONNECT` rejections (such as `407` for authentication failures or `403` when a destination is blocked) surface as errors from `client.Do`.
- **Logging raw proxy URLs in errors.** Avoid formatting `rawURL` into error messages or logs — log only `u.Host` so passwords never leak.

## Calling an API through a Relay URL

When you want zero proxy configuration, create a Relay in the dashboard ([IP addresses](https://my.prontaro.com/ips)) and call it with a standard `http.Client`:

```go
req, err := http.NewRequestWithContext(ctx, http.MethodGet, os.Getenv("PRONTARO_RELAY_URL")+"/v1/status", nil)
if err != nil {
	return err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("PARTNER_API_TOKEN"))
// Include only if you set a password (in the dashboard under IP addresses → Relay address → Access):
req.Header.Set("Prontaro-Relay-Auth", os.Getenv("RELAY_LOGIN")+":"+os.Getenv("RELAY_PASSWORD"))
```

See [Relay URLs](https://prontaro.com/docs/outbound/relay.md) for TLS termination details and limits.

## Next steps

- [curl and environment variables](https://prontaro.com/docs/languages/curl.md) — diagnose `407` and `403` errors with `curl -v`.
- [HTTP & SOCKS5 proxy](https://prontaro.com/docs/outbound/proxy.md) — configure `access`, `targets`, and credential rotation.
- [Local port forwarding (prontaro forward)](https://prontaro.com/docs/outbound/forward.md) — alternative when a database driver does not accept a custom `DialContext`.
