tinywasm/fetch allows you to simplify your requests by using a base URL and providing only the endpoint.
When building the final URL, the following priority is used:
- Absolute URL: If the endpoint passed to
Get,Post, etc., starts withhttp://orhttps://, it is used directly. - Request BaseURL: If
.BaseURL("...")is called on the request builder. - Global BaseURL: If
fetch.SetBaseURL("...")was called previously. - WASM Origin: In WebAssembly environments (browsers), it defaults to
location.origin. - Error: If none of the above are available, the request will fail with an error.
You can set a global base URL once at the start of your application:
import "github.com/tinywasm/fetch"
func check() {
fetch.SetBaseURL("https://api.example.com")
// Request to https://api.example.com/users
fetch.Get("/users").Send(...)
}You can override the global base URL for a specific request:
fetch.Get("/data").
BaseURL("https://other-api.com").
Send(...)In a browser, if you don't set a base URL, it automatically uses the current origin:
// In browser at https://myapp.com
// Request to https://myapp.com/api/v1/status
fetch.Get("/api/v1/status").Send(...)You can pass structures that implement the EndpointProvider interface directly:
type User struct {
ID string
}
func (u User) HandlerName() string {
return "/users"
}
func main() {
user := User{ID: "123"}
// Automatically uses "/users" as the endpoint
fetch.Get(user).Send(...)
}This is useful for creating type-safe API clients where the structure itself knows its endpoint.