stew/* Packages / 14.11
🌐 stew/net
The stew/net package is a type-safe wrapper around the browser's Fetch API, allowing asynchronous HTTP requests with synchronous Go syntax.
Concept: Simplifying Asynchrony
In JavaScript, fetch returns Promises (Promise) requiring .then() or await.
In Stew, we use a synchronization bridge via Go channels.
Internal mechanism: When a
net.Get call is made, the Go-routine is paused (blocked on a channel) while the browser performs the request. As soon as the JS Promise is resolved, the result is injected back into the channel, transparently unblocking the Go-routine.
Typed Requests (Generics)
Use Go generics to automatically deserialize JSON into your own structures.
<goscript client>
import "stew/net"
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
loadData := func() {
user, err := net.Get[User]("https://api.example.com/me")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("User:", user.Name)
}
</goscript>
Supported Methods
net.Get[T](url)
Retrieves a resource.
net.Post[T](url, body)
Sends data (JSON auto-marshaling).
net.Put[T](url, body)
Updates an existing resource entirely.
net.Patch[T](url, body)
Partially updates a resource.
net.Delete[T](url)
Removes a resource.
net.Fetch(url, opts)
Raw Fetch API access (Headers, etc.).
Reactive Observation: net.Watch
Creates a Signal that automatically updates at a regular interval. Ideal for dashboards or live data feeds.
<goscript client>
import "stew/net"
import "time"
// Poll the API every 5 seconds
stats := net.Watch[Stats]("https://api.site.com/stats", 5*time.Second)
</goscript>
<p>Current visitors: {{ stats.Get().Visits }}</p>
Network State: net.IsLoading
A global bool Signal that becomes true whenever a stew/net request is in progress.
<goscript client>
import "stew/net"
</goscript>
{{ if net.IsLoading.Get() }}
<div class="spinner">Loading...</div>
{{ end }}