Exposing a Go Agent over HTTP
Overview
HTTP mounting is metadata only: you declare, on the agent's definition, a URL prefix for the agent and a route for each method. The platform routes matching requests to the right instance and method — there is no incoming-request handler to write. To handle raw requests yourself (a net/http handler, streaming bodies, a website), use an HTTP router instead (see golem-http-router-go).
Two pieces, both on the definition:
Spec.HTTP = &golem.Mount{Path: "…"} — the agent-level prefix. Its {var} segments bind the agent's user-supplied constructor (ID) fields, so a request URL selects the instance. Every user-supplied ID field must appear as a {var}; exclude auto-injected golem.Principal fields.
golem.HTTP(golem.GET("/suffix"), …) as a method option — one or more routes per method, with request data bound to the method's input fields.
Steps
- Add a mount to the agent's
Spec: HTTP: &golem.Mount{Path: "/counters/{name}"}.
- Add routes to methods with the
golem.HTTP(...) option and a verb constructor.
- Bind request data to input fields (path
{var}, golem.Query, golem.Header, or the JSON body).
- Build, then deploy behind an HTTP API so the routes are served.
Example (definition)
package counter
import "github.com/golemcloud/golem/sdks/go/golem"
type ID struct{ Name string } // bound by {name} in the mount path
type AddIn struct{ By int64 }
var Agent = golem.DefineAgent[ID](golem.Spec{
Name: "CounterAgent",
Description: "A counter exposed over HTTP",
// {name} binds ID.Name; CORS/Auth optional.
HTTP: &golem.Mount{Path: "/counters/{name}", CORS: []string{"*"}},
})
var (
// GET /counters/{name}/value — options compose: Desc + HTTP in one call.
Value = Agent.Method[golem.Unit, int64]("value", golem.Description("Read the current value"), golem.HTTP(golem.GET("/value")))
// POST /counters/{name}/add — AddIn arrives as the JSON body
Add = Agent.Method[AddIn, int64]("add", golem.Description("Add to the count"), golem.HTTP(golem.POST("/add")))
)
The handlers are ordinary handlers (see golem-add-agent-go) — nothing HTTP-specific in the impl.
Binding request data to input fields
- Path variables —
{sku} in a route suffix binds the input field SKU: golem.GET("/items/{sku}").
- Query parameters —
golem.Query("detailed", "detailed") binds ?detailed= to the Detailed field:Lookup = Agent.Method[LookupIn, ItemInfo]("lookup", golem.HTTP(golem.GET("/items/{sku}", golem.Query("detailed", "detailed"))))
- Headers —
golem.Header("X-Tenant", "tenant") binds the header to the Tenant field.
- Body — for body-carrying verbs (
POST/PUT), user-supplied input fields not bound to path/query/header come from the JSON request body.
- Principal — the host injects
golem.Principal fields in ID and method inputs. Do not send them in the body or bind them to path/query/header; explicit principal bindings are rejected.
Auth & CORS
Verbs
golem.GET, golem.POST, golem.PUT, golem.DELETE, and golem.Custom("VERB", "/path"). GET/HEAD are bodyless — bind all user-supplied inputs from path/query/header, excluding auto-injected golem.Principal.
Durable Stream Route Customization
A method that takes or returns golem.AgentStreams is served as a Durable Streams URL family. golem.DurableStreams customizes it:
type UploadIn struct {
Chunks golem.AgentStream[byte]
File string
}
Upload = Agent.Method[UploadIn, int64]("upload",
golem.HTTP(golem.POST("/upload?file={file}", golem.DurableStreams(golem.StreamRoute{
Slots: []golem.StreamSlot{
{Input: "chunks", Name: "data", ContentType: "application/vnd.example.media"},
{Result: true, Name: "size"},
},
NoStreamDelete: true,
NoInvocationDelete: true,
MaxReadersPerStream: 8,
}))))
- A slot is selected by exactly one of
Input (an AgentStream input field, by the same schema name golem.Query/golem.Header bind), Output (an AgentStream field of the returned struct) or Result: true (the returned value itself).
Name changes the public URL and OpenAPI name; the canonical name is no longer accepted.
ContentType is allowed only for a direct AgentStream[byte] slot and must be a concrete non-text, non-JSON MIME type without parameters or wildcards. Other streams stay application/json. SSE still uses text/event-stream with base64 data.
NoExternalWrites, NoStreamDelete and NoInvocationDelete remove that protocol operation (405 with an exact Allow header); leaving them false keeps the operation.
MaxReadersPerStream is 1 through 16 and applies to long-poll and SSE. MaxAppendsPerSecond must not be combined with NoExternalWrites. A limit rejection is 429 with Retry-After: 1; limits are per route and worker-service node, not cluster-wide.
- A stream input cannot be bound from the path, query or a header.
Serving the Agent's Own Files
Mount.ExposeFiles serves files from the agent's filesystem under its mount, without calling a method:
var Agent = golem.DefineAgent[ID](golem.Spec{
Name: "MediaAgent",
HTTP: &golem.Mount{
Path: "/media/{name}",
ExposeFiles: []golem.FileMapping{
{Route: "/latest", Path: "/latest.txt"}, // one file
{Route: "/files/*", Path: "/public/$1"}, // a directory tree
},
},
})
- The agent must be durable and not a phantom, and every user-supplied
ID field must be a scalar captured exactly once by Mount.Path (no {*rest}), so a request names exactly one agent. Exclude auto-injected golem.Principal fields.
- Mappings are tried in order; repeating a route with another path gives a fallback. A subtree route ends in
/* and its path in /$1.
- Only
GET and HEAD are served, with ranges and conditional requests. There is no directory listing, implicit index file or symlink following — expose only directories meant for HTTP.
- Files the constructor or a method writes (with
os.WriteFile) are served as they change.
Mount.FileResponseHeaders adds response headers, in order, to every file served: []golem.FileResponseHeader{{Name: "content-security-policy", Value: "default-src 'none'"}}. Headers the platform manages itself (content-type, cache-control, etag, the CORS headers, …) are rejected at deploy.
Key Constraints
- Every user-supplied
ID field must appear as a {var} in Mount.Path (else the platform can't identify the instance), excluding auto-injected golem.Principal. Mount segments may be literals or named variables, but never a catch-all. A trailing {*rest} is allowed only in an endpoint suffix.
- A method with an HTTP endpoint but no agent-level
Spec.HTTP mount is a definition error — set the mount.
- Serving the routes requires an HTTP API deployment (see the manifest
httpApi configuration); mounting alone only advertises the routes.
Related Skills
| Skill |
When to Load |
golem-add-agent-go |
Define the agent whose methods you're exposing |
golem-make-http-request-go |
Make an outgoing HTTP request from agent code |
golem-multi-instance-agent-go |
The {var} path segments select an instance by ID |
1---2name: golem-add-http-endpoint-go3description: "Exposing a Go agent's methods over HTTP. Use when the user wants to add an HTTP endpoint/route to an agent, mount an agent under a URL path, make agent methods callable over HTTP, or map path/query/header parameters in a Go Golem project."4metadata:5 source: https://skillmd.com/skills/golemcloud/golem-add-http-endpoint-go6---78# Exposing a Go Agent over HTTP910## Overview1112HTTP mounting is **metadata only**: you declare, on the agent's definition, a URL prefix for the agent and a route for each method. The platform routes matching requests to the right instance and method — there is no incoming-request handler to write. To handle raw requests yourself (a `net/http` handler, streaming bodies, a website), use an HTTP router instead (see `golem-http-router-go`).1314Two pieces, both on the **definition**:15161. `Spec.HTTP = &golem.Mount{Path: "…"}` — the agent-level prefix. Its `{var}` segments bind the agent's user-supplied constructor (`ID`) fields, so a request URL selects the instance. **Every user-supplied `ID` field must appear as a `{var}`; exclude auto-injected `golem.Principal` fields.**172. `golem.HTTP(golem.GET("/suffix"), …)` as a method option — one or more routes per method, with request data bound to the method's input fields.1819## Steps20211. **Add a mount** to the agent's `Spec`: `HTTP: &golem.Mount{Path: "/counters/{name}"}`.222. **Add routes** to methods with the `golem.HTTP(...)` option and a verb constructor.233. **Bind request data** to input fields (path `{var}`, `golem.Query`, `golem.Header`, or the JSON body).244. **Build**, then **deploy behind an HTTP API** so the routes are served.2526## Example (definition)2728```go29package counter3031import "github.com/golemcloud/golem/sdks/go/golem"3233type ID struct{ Name string } // bound by {name} in the mount path3435type AddIn struct{ By int64 }3637var Agent = golem.DefineAgent[ID](golem.Spec{38 Name: "CounterAgent",39 Description: "A counter exposed over HTTP",40 // {name} binds ID.Name; CORS/Auth optional.41 HTTP: &golem.Mount{Path: "/counters/{name}", CORS: []string{"*"}},42})4344var (45 // GET /counters/{name}/value — options compose: Desc + HTTP in one call.46 Value = Agent.Method[golem.Unit, int64]("value", golem.Description("Read the current value"), golem.HTTP(golem.GET("/value")))4748 // POST /counters/{name}/add — AddIn arrives as the JSON body49 Add = Agent.Method[AddIn, int64]("add", golem.Description("Add to the count"), golem.HTTP(golem.POST("/add")))50)51```5253The handlers are ordinary handlers (see `golem-add-agent-go`) — nothing HTTP-specific in the impl.5455## Binding request data to input fields5657- **Path variables** — `{sku}` in a route suffix binds the input field `SKU`: `golem.GET("/items/{sku}")`.58- **Query parameters** — `golem.Query("detailed", "detailed")` binds `?detailed=` to the `Detailed` field:59 ```go60 Lookup = Agent.Method[LookupIn, ItemInfo]("lookup", golem.HTTP(golem.GET("/items/{sku}", golem.Query("detailed", "detailed"))))61 ```62- **Headers** — `golem.Header("X-Tenant", "tenant")` binds the header to the `Tenant` field.63- **Body** — for body-carrying verbs (`POST`/`PUT`), user-supplied input fields not bound to path/query/header come from the JSON request body.64- **Principal** — the host injects `golem.Principal` fields in `ID` and method inputs. Do not send them in the body or bind them to path/query/header; explicit principal bindings are rejected.6566## Auth & CORS6768- `Mount{Auth: true}` requires auth on every endpoint; `golem.EndpointAuth(true|false)` overrides it per route:69 ```go70 golem.HTTP(golem.GET("/items/{sku}", golem.EndpointAuth(true)))71 ```72- `Mount{CORS: []string{"*"}}` sets allowed origins for the agent; `golem.EndpointCORS(patterns...)` adds patterns for one route.7374## Verbs7576`golem.GET`, `golem.POST`, `golem.PUT`, `golem.DELETE`, and `golem.Custom("VERB", "/path")`. `GET`/`HEAD` are bodyless — bind all user-supplied inputs from path/query/header, excluding auto-injected `golem.Principal`.7778## Durable Stream Route Customization7980A method that takes or returns `golem.AgentStream`s is served as a Durable Streams URL family. `golem.DurableStreams` customizes it:8182```go83type UploadIn struct {84 Chunks golem.AgentStream[byte]85 File string86}8788Upload = Agent.Method[UploadIn, int64]("upload",89 golem.HTTP(golem.POST("/upload?file={file}", golem.DurableStreams(golem.StreamRoute{90 Slots: []golem.StreamSlot{91 {Input: "chunks", Name: "data", ContentType: "application/vnd.example.media"},92 {Result: true, Name: "size"},93 },94 NoStreamDelete: true,95 NoInvocationDelete: true,96 MaxReadersPerStream: 8,97 }))))98```99100- A slot is selected by exactly one of `Input` (an `AgentStream` input field, by the same schema name `golem.Query`/`golem.Header` bind), `Output` (an `AgentStream` field of the returned struct) or `Result: true` (the returned value itself).101- `Name` changes the public URL and OpenAPI name; the canonical name is no longer accepted.102- `ContentType` is allowed only for a direct `AgentStream[byte]` slot and must be a concrete non-text, non-JSON MIME type without parameters or wildcards. Other streams stay `application/json`. SSE still uses `text/event-stream` with base64 data.103- `NoExternalWrites`, `NoStreamDelete` and `NoInvocationDelete` remove that protocol operation (`405` with an exact `Allow` header); leaving them `false` keeps the operation.104- `MaxReadersPerStream` is 1 through 16 and applies to long-poll and SSE. `MaxAppendsPerSecond` must not be combined with `NoExternalWrites`. A limit rejection is `429` with `Retry-After: 1`; limits are per route and worker-service node, not cluster-wide.105- A stream input cannot be bound from the path, query or a header.106107## Serving the Agent's Own Files108109`Mount.ExposeFiles` serves files from the agent's filesystem under its mount, without calling a method:110111```go112var Agent = golem.DefineAgent[ID](golem.Spec{113 Name: "MediaAgent",114 HTTP: &golem.Mount{115 Path: "/media/{name}",116 ExposeFiles: []golem.FileMapping{117 {Route: "/latest", Path: "/latest.txt"}, // one file118 {Route: "/files/*", Path: "/public/$1"}, // a directory tree119 },120 },121})122```123124- The agent must be durable and not a phantom, and every user-supplied `ID` field must be a scalar captured exactly once by `Mount.Path` (no `{*rest}`), so a request names exactly one agent. Exclude auto-injected `golem.Principal` fields.125- Mappings are tried in order; repeating a route with another path gives a fallback. A subtree route ends in `/*` and its path in `/$1`.126- Only `GET` and `HEAD` are served, with ranges and conditional requests. There is no directory listing, implicit index file or symlink following — expose only directories meant for HTTP.127- Files the constructor or a method writes (with `os.WriteFile`) are served as they change.128- `Mount.FileResponseHeaders` adds response headers, in order, to every file served: `[]golem.FileResponseHeader{{Name: "content-security-policy", Value: "default-src 'none'"}}`. Headers the platform manages itself (`content-type`, `cache-control`, `etag`, the CORS headers, …) are rejected at deploy.129130## Key Constraints131132- Every user-supplied `ID` field must appear as a `{var}` in `Mount.Path` (else the platform can't identify the instance), excluding auto-injected `golem.Principal`. Mount segments may be literals or named variables, but never a catch-all. A trailing `{*rest}` is allowed only in an endpoint suffix.133- A method with an HTTP endpoint but no agent-level `Spec.HTTP` mount is a definition error — set the mount.134- Serving the routes requires an HTTP API deployment (see the manifest `httpApi` configuration); mounting alone only advertises the routes.135136### Related Skills137138| Skill | When to Load |139|-------|--------------|140| `golem-add-agent-go` | Define the agent whose methods you're exposing |141| `golem-make-http-request-go` | Make an *outgoing* HTTP request from agent code |142| `golem-multi-instance-agent-go` | The `{var}` path segments select an instance by ID |