Wrapping Go functions as HTTP handlers, CLI commands, and more
go-function is a Go library that provides utilities for wrapping any Go function to enable multiple calling conventions: direct calls with typed arguments, string-based calls, JSON calls, HTTP handlers, and CLI commands.
- Multiple Calling Conventions: Call functions with
[]any, strings, named strings, or JSON - Automatic Type Conversion: Convert strings to the correct types automatically
- HTTP Integration: Turn functions into HTTP handlers with
httpfunpackage - CLI Integration: Build command-line interfaces with
clipackage - HTML Forms: Generate HTML forms for quick internal dashboards with the separate module go-htmlform
- Code Generation: Generate zero-overhead wrappers with
gen-func-wrappers - Reflection Fallback: Use reflection-based wrappers when code generation isn't needed
- Context Support: Automatic
context.Contexthandling - Error Handling: Proper error propagation and panic recovery
go get github.com/domonda/go-functionThe changes of every release are listed in CHANGELOG.md.
- Tutorial: One function, four interfaces: build a program whose one function runs as Go call, CLI command, JSON API, and HTML form
- How-to guides: switch to generated wrappers, make your own types scannable, customize HTTP error responses
- Reference: calling conventions, string conversion, HTTP status codes
- Explanation: architecture, security model
- API: pkg.go.dev, and the gen-func-wrappers README
All documents are listed in docs/README.md.
package main
import (
"context"
"fmt"
"github.com/domonda/go-function"
)
func Add(a, b int) int {
return a + b
}
func Greet(ctx context.Context, name string) (string, error) {
return fmt.Sprintf("Hello, %s!", name), nil
}
func main() {
// Wrap functions using reflection,
// passing the argument names (including "ctx" for a context.Context)
addWrapper := function.MustReflectWrapper(Add, "a", "b")
greetWrapper := function.MustReflectWrapper(Greet, "ctx", "name")
ctx := context.Background()
// Call with string arguments
results, _ := addWrapper.CallWithStrings(ctx, "5", "3")
fmt.Println(results[0]) // Output: 8
// Call with named arguments
results, _ = greetWrapper.CallWithNamedStrings(ctx, map[string]string{
"name": "World",
})
fmt.Println(results[0]) // Output: Hello, World!
// Call with a JSON object of named arguments
results, _ = addWrapper.CallWithJSON(ctx, []byte(`{"a": 10, "b": 20}`))
fmt.Println(results[0]) // Output: 30
}package main
import (
"context"
"fmt"
"net/http"
"github.com/domonda/go-function"
"github.com/domonda/go-function/httpfun"
)
func Calculate(ctx context.Context, operation string, a, b int) (int, error) {
switch operation {
case "add":
return a + b, nil
case "multiply":
return a * b, nil
default:
return 0, fmt.Errorf("unknown operation: %s", operation)
}
}
func main() {
calculate := function.MustReflectWrapper(Calculate, "ctx", "operation", "a", "b")
// Create HTTP handlers from the function that get the arguments
// from the URL query or from the fields of a JSON object request body
// and respond with the result as JSON
http.Handle("GET /calculate", httpfun.Handler(httpfun.RequestQueryArgs, calculate, httpfun.RespondJSON))
http.Handle("POST /calculate", httpfun.Handler(httpfun.RequestBodyJSONFieldsAsArgs, calculate, httpfun.RespondJSON))
http.ListenAndServe(":8080", nil)
// Usage:
// GET /calculate?operation=add&a=5&b=3 -> 8
// POST /calculate with JSON: {"operation":"multiply","a":5,"b":3} -> 15
}package main
import (
"context"
"fmt"
"os"
"github.com/domonda/go-function"
"github.com/domonda/go-function/cli"
)
func Deploy(env, service string, version int) error {
fmt.Printf("Deploying %s v%d to %s\n", service, version, env)
return nil
}
func main() {
dispatcher := cli.NewStringArgsDispatcher("myapp")
dispatcher.MustAddCommand(
"deploy",
"Deploy a service version to an environment",
function.MustReflectWrapper(Deploy, "env", "service", "version"),
)
command, err := dispatcher.DispatchCombinedCommandAndArgs(context.Background(), os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "Error in %s: %v\n", command, err)
os.Exit(1)
}
}
// Usage:
// $ myapp deploy production api-server 42
// Deploying api-server v42 to productionFor production use, generate optimized wrappers without reflection overhead:
// In your code, use placeholder functions
package myapp
import "github.com/domonda/go-function"
func Calculate(a, b int) int {
return a + b
}
// Use WrapperTODO during development
var CalculateWrapper = function.WrapperTODO(Calculate)Then add the code generator as a tool of your module and run it:
go get -tool github.com/domonda/go-function/cmd/gen-func-wrappers@latest
go tool gen-func-wrappers ./...This replaces WrapperTODO calls with generated, type-safe wrapper code that has zero reflection overhead.
The library supports various function signatures:
// No arguments or results
func SimpleFunc()
// With context
func WithContext(ctx context.Context, arg string) error
// Multiple arguments and results
func Complex(ctx context.Context, a int, b string) (result int, err error)
// Variadic functions (Call takes the variadic arguments as one slice argument,
// CallWithStrings takes every string from the variadic position on as one element)
func Variadic(args ...string) stringRequirements:
- If present,
context.Contextmust be the first argument - If present,
errormust be the last result - All arguments and results must be supported types (or implement
encoding.TextUnmarshaler/json.Unmarshaler)
Wrapper- Main interface for wrapped functionsDescription- Function metadata (name, arguments, types)StringScanner- String-to-type conversionReflectWrapper- Reflection-based wrapperWrapperTODO- Placeholder for code generation
Handler- Create HTTP handler from functionHandlerNoWrapper- HTTP handler for afunc(context.Context) ([]byte, error)RequestArgsFunc- Parse function arguments from HTTP requestsResultsWriter- Write function results as HTTP responses
StringArgsDispatcher- Command dispatcher for CLI appsSuperStringArgsDispatcher- Multi-level command dispatcherCompleteStringArgsDispatcher/CompleteSuperStringArgsDispatcher- Shell completion support
HTML forms for wrapped functions moved to the separate module
github.com/domonda/go-htmlform,
meant for quick internal dashboards. Its last release from this repository
is htmlform/v0.7.1.
- Generates optimized wrapper code
- Zero reflection overhead
- Preserves type safety
- Supports custom import prefixes
- Documentation: cmd/gen-func-wrappers/README.md
The library automatically converts strings to the required types:
// Basic types
var i int
function.ScanString("42", &i) // i = 42
var f float64
function.ScanString("3.14", &f) // f = 3.14
var b bool
function.ScanString("true", &b) // b = true
// Time types
var t time.Time
function.ScanString("2024-01-15", &t)
var d time.Duration
function.ScanString("5m30s", &d) // d = 5*time.Minute + 30*time.Second
// Slices
var nums []int
function.ScanString("[1,2,3]", &nums) // nums = []int{1,2,3}
// Structs (as JSON)
type Person struct {
Name string
Age int
}
var p Person
function.ScanString(`{"Name":"Alice","Age":30}`, &p)
// Nil values
var ptr *int
function.ScanString("nil", &ptr) // ptr = nilBut you can customize type to string conversions:
import "github.com/domonda/go-function"
// Add custom scanner for a specific type
function.StringScanners = function.StringScanners.WithTypeScanner(
reflect.TypeFor[MyCustomType](),
function.StringScannerFunc(func(src string, dest any) error {
// Custom conversion logic, dest is a *MyCustomType
return nil
}),
)
// Configure time formats
function.TimeFormats = []string{
time.RFC3339,
"2006-01-02",
"2006-01-02 15:04",
}
// Configure the time zone used when a parsed timestamp has no zone of its own.
// Defaults to time.Local; set at process start if you want naive timestamps
// (e.g. "2024-01-15 10:00:00") interpreted in UTC instead.
function.TimeLocation = time.UTCimport (
"log"
"net/http"
"github.com/domonda/go-function/httpfun"
)
// Pretty-print JSON responses
httpfun.PrettyPrint = true
httpfun.PrettyPrintIndent = " "
// Custom error handler, delegating to the default
// that answers invalid arguments with 400 Bad Request
httpfun.HandleError = func(err error, w http.ResponseWriter, r *http.Request) bool {
log.Printf("HTTP error: %v", err)
return httpfun.DefaultHandleError(err, w, r)
}
// Panic recovery
httpfun.CatchHandlerPanics = true
// Request body size limits, larger requests are answered with 413
httpfun.MaxRequestBodySize = 32 << 20 // RequestBodyAsArg and RequestBodyJSONFieldsAsArgs, default 32 MiB, <= 0 disables it
httpfun.MaxMultipartFormSize = 32 << 20 // RequestMultipartFormArgs total request body cap, default 32 MiB
httpfun.MaxMultipartFormMemory = 1 << 20 // in-memory threshold, default 1 MiB// Custom handler that always returns uppercase strings
customHandler := httpfun.ResultsWriterFunc(func(results []any, resultErr error, w http.ResponseWriter, r *http.Request) error {
if resultErr == nil && len(results) > 0 {
if str, ok := results[0].(string); ok {
_, err := w.Write([]byte(strings.ToUpper(str)))
return err
}
}
return httpfun.RespondJSON(results, resultErr, w, r)
})
handler := httpfun.Handler(httpfun.RequestQueryArgs, wrapper, customHandler)// Given the functions:
// func CreateUser(ctx context.Context, name string) error
// func DeleteUser(ctx context.Context, name string) error
// func Migrate(ctx context.Context) error
// func Seed(ctx context.Context) error
// Build CLI with subcommands: app user create, app user delete, etc.
dispatcher := cli.NewSuperStringArgsDispatcher("app")
userDispatcher := dispatcher.MustAddSuperCommand("user")
userDispatcher.MustAddCommand("create", "Create a user", function.MustReflectWrapper(CreateUser, "ctx", "name"))
userDispatcher.MustAddCommand("delete", "Delete a user", function.MustReflectWrapper(DeleteUser, "ctx", "name"))
dbDispatcher := dispatcher.MustAddSuperCommand("db")
dbDispatcher.MustAddCommand("migrate", "Migrate the database", function.MustReflectWrapper(Migrate))
dbDispatcher.MustAddCommand("seed", "Seed the database", function.MustReflectWrapper(Seed))
superCommand, command, err := dispatcher.DispatchCombinedCommandAndArgs(context.Background(), os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "%s %s: %v\n", superCommand, command, err)
os.Exit(1)
}The library includes comprehensive tests. Run the tests of all modules of the workspace with:
./test-workspace.shgo test ./... in the repository root only tests the root module.
Contributions are welcome! Please:
- Add tests for new features
- Update documentation
- Follow existing code style
- Ensure
./test-workspace.shpasses
MIT License - see LICENSE file for details
- go-types - Type definitions with string scanning support
- go-astvisit - AST manipulation utilities used by the code generator