HandleAPI Function
Understand how to write the Go function that powers each API route.
Function Signature
func HandleAPI(r *http.Request, params map[string]string) (interface{}, error)
r
: the incoming HTTP requestparams
: URL parameters extracted from dynamic folders (e.g._id
)- Return: any value encodable to JSON (struct, map, slice, etc.)
The returned value is automatically JSON-encoded and sent as the response.
On error, return nil
and an error value — Barry will return a 500 status code.
Example with Parameters
// api/user/_id/index.go
package user
import "net/http"
func HandleAPI(r *http.Request, params map[string]string) (interface{}, error) {
id := params["id"]
return map[string]interface{}{
"user_id": id,
}, nil
}
Request to /api/user/42
will return:
{"user_id":"42"}