Skip to content

Networking

Follow the network’s state, load data off the main goroutine, discover local services and download in the background.

cx.Env().Network() reports whether the system has a usable route (Online) and whether it considers that route metered or expensive (Expensive). Bindings follow it like any other environment value. cx.OnNetworkChange(func(core.Network)) calls the handler on the engine’s goroutine for each change while its scope lives. The system’s route says nothing about whether a particular server answers. A target that cannot report connectivity defaults to online, and unknown cost defaults to false.

Set core.Environment{Network: &core.Network{Online: false}} through nsgotest.Environment or App.SetEnvironment to test offline behavior.

Go’s own net/http makes requests on every target, with the system’s TLS and proxy settings. Signals belong to the engine’s goroutine, so a response from another goroutine reaches them through cx.Post.

go func() {
resp, err := http.Get("https://api.example.com/items")
if err != nil {
cx.Post(func() { errText.Set(err.Error()) })
return
}
defer resp.Body.Close()
var items []Item
if err := json.NewDecoder(resp.Body).Decode(&items); err != nil {
cx.Post(func() { errText.Set(err.Error()) })
return
}
cx.Post(func() { list.Set(items) })
}()

cx.Post runs its function on the graph’s goroutine, where signals may be set, and skips it if the scope has since been disposed. A worker can read cx.Disposed(), but a false result does not keep the scope alive. On Android the manifest asks for the internet permission, and image downloads cache themselves on disk.

core.NewResource does the same for a value loaded from a source. Its fetcher runs on a goroutine of its own and loads again when the source changes:

items := core.NewResource(cx, func() (string, bool) { return query.Get(), query.Get() != "" },
func(ctx context.Context, q string, _ core.ResourceInfo) ([]Item, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://api.example.com/items?q="+url.QueryEscape(q), nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var list []Item
if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
return nil, err
}
return list, nil
})

items.Get(), items.Err() and items.Loading() are signals that bindings follow. A new query cancels the request still running through ctx, so a late answer never replaces a newer one. items.Refetch() retries, keeping the last list while it loads, and items.Mutate sets a value at once for an optimistic update.

core.Suspense shows a fallback while the resources its content reads load their first value, so a screen needs no loading flag of its own:

core.Suspense{
Content: func(cx *core.Scope) core.Node { return itemList(cx, items) },
Fallback: func(*core.Scope) core.Node { return ui.Spinner{Label: "Loading"} },
}

The content stays mounted but hidden while it waits, so it shows at once when the values arrive. A refetch keeps it shown with the last value.

On macOS, iOS, Android, Windows and Linux, cx.AdvertiseService publishes a listening port and TXT attributes. cx.BrowseServices reports resolved services with their host, port and TXT attributes. Host may be a DNS hostname or an IP address. When a service leaves, the callback receives it again with Removed set. Check cx.Env().CanDiscoverServices() for platform support. Both calls return a stop function and end when their scope is disposed. A platform error is reported asynchronously on the engine goroutine. Linux uses Avahi and reports an error if the daemon is unavailable.

For Bonjour on Apple platforms, declare the service types and explain local network access in nsgo.yaml. The system manages the permission prompt and remembers the user’s choice; to ask ahead of the first connection and learn the answer, request core.PermissionLocalNetwork.

apple:
info:
NSLocalNetworkUsageDescription: Finds nearby devices to sync with.
NSBonjourServices:
- _example._tcp

Android uses NsdManager. Android 12 and earlier and Android 13 before T Extensions 7 require CHANGE_WIFI_MULTICAST_STATE for Wi-Fi discovery. Standalone builds declare that permission. If you embed NSGo in an Android host, add it to the host manifest for those devices. Advertised TXT values must be valid UTF-8 on devices without Android’s raw TXT API (API 37 or T Extensions 22). Browsing preserves raw TXT values. If an Android host targets API 37 or higher, it must declare and request ACCESS_LOCAL_NETWORK on Android 17 or later.

Use nsgotest.LocalServices to supply browse results in a headless test.

Use cx.Download and cx.OnDownloadUpdate in standalone iOS and macOS apps, and on Android. Embedded Apple views have no transfer host. Android apps enable android.background_downloads: true in nsgo.yaml. Start a download from a user action while the app is visible. Use an absolute destination with an existing parent directory the app can write.

cx.OnDownloadUpdate(func(p core.DownloadProgress) {
progress.Set(p)
})
task, err := cx.Download(core.DownloadRequest{URL: url}, path, core.DownloadOptions{
CertificatePEM: serverCertificate,
})

The transfer uses GET and accepts optional request headers. It uses the normal HTTPS trust store unless CertificatePEM pins the server’s leaf certificate. The pin also requires a matching hostname and a valid certificate. Use the final URL as the service requires a successful response from that URL.

On Apple, a self-signed certificate at a public hostname needs an App Transport Security exception for that host in apple.info. The transfer still checks its exact certificate pin, hostname and validity. A local NAS connection also needs an NSLocalNetworkUsageDescription explaining access, and unqualified or .local hosts use NSAllowsLocalNetworking. Apple’s ATS settings

apple:
info:
NSAppTransportSecurity:
NSExceptionDomains:
files.example.com:
NSExceptionAllowsInsecureHTTPLoads: true

The Android foreground service continues after the activity leaves the screen. It posts a progress notification, subject to Android’s notification permission. Progress uses byte counts and sets Total to -1 until known. Success atomically replaces the destination. task.Pause() keeps the partial file, task.Resume() uses an HTTP range when the server supplies a validator, and task.Cancel() removes the partial file.

iOS uses a system background URLSession that continues transfers while the app is suspended. The app reconnects its session on launch and publishes files before acknowledging background completion. macOS transfers run in process. Apple platforms use native resume data for paused downloads and keep request metadata in private app storage until a terminal result is saved. A server that cannot resume starts the transfer again.

Register OnDownloadUpdate again when the app starts to see active tasks and saved results. Use p.Task.Forget() after handling a final result. Android can stop the service, for example when its foreground transfer time expires. The app then receives DownloadInterrupted. On Windows, Linux, tvOS, watchOS and the web, Download returns ErrDownloadUnavailable.

Apps that run their own Go transfer engine (such as resumable net/http downloads, chunked uploads or sync queues) can keep Android’s Go process alive across backgrounding and Activity destruction with mobile.StartDataSync. Enable android.data_sync: true in nsgo.yaml to declare DataSyncService (foregroundServiceType="dataSync") together with FOREGROUND_SERVICE, FOREGROUND_SERVICE_DATA_SYNC and POST_NOTIFICATIONS.

ds, err := mobile.StartDataSync(mobile.DataSyncOptions{
Notification: mobile.DataSyncNotification{
Title: "Syncing files",
Body: "Preparing transfer...",
Indeterminate: true,
},
OnTimeout: func() {
flushTransferCheckpoints()
},
})
if err != nil {
// mobile.ErrDataSyncNotAllowed when started outside an eligible foreground state;
// mobile.ErrDataSyncUnavailable when android.data_sync is not enabled.
return err
}
defer ds.Stop()
ds.Update(mobile.DataSyncNotification{
Title: "Syncing files",
Body: "archive.zip",
Current: sentBytes,
Total: totalBytes,
})

Sessions are reference-counted: concurrent transfers can each call mobile.StartDataSync and share one foreground service and progress notification until the last handle calls Stop(). Set Total > 0 for determinate progress, Indeterminate: true (or Total < 0) for an indeterminate progress bar, or Total == 0 with Indeterminate: false for text only. On Android 15 (API 35+), OnTimeout runs when Android’s dataSync foreground quota expires so the app can flush checkpoints before the service stops. To hold a PARTIAL_WAKE_LOCK during screen-off transfers, add WAKE_LOCK to android.permissions and set WakeLock: true. mobile.DataSyncSupported() checks whether the Android service is declared; on non-Android platforms mobile.StartDataSync returns a safe no-op handle with a nil error.