Skip to content

About

Wrapping Go functions as HTTP handlers and CLI commands

Resources

Stars

1 star

Watchers

1 watching

Forks

Latest commit

 

History

194 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

go-function

Go Reference Go Report Card

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.

Features

  • 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 httpfun package
  • CLI Integration: Build command-line interfaces with cli package
  • 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.Context handling
  • Error Handling: Proper error propagation and panic recovery

Installation

go get github.com/domonda/go-function

The changes of every release are listed in CHANGELOG.md.

Documentation

All documents are listed in docs/README.md.

Quick Start

Basic Function Wrapping

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
}

HTTP Handler

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
}

CLI Command

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 production

Code Generation for Better Performance

For 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.

Supported Function Signatures

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) string

Requirements:

  • If present, context.Context must be the first argument
  • If present, error must be the last result
  • All arguments and results must be supported types (or implement encoding.TextUnmarshaler / json.Unmarshaler)

Packages

Core Package (function)

  • Wrapper - Main interface for wrapped functions
  • Description - Function metadata (name, arguments, types)
  • StringScanner - String-to-type conversion
  • ReflectWrapper - Reflection-based wrapper
  • WrapperTODO - Placeholder for code generation

HTTP Package (httpfun)

  • Handler - Create HTTP handler from function
  • HandlerNoWrapper - HTTP handler for a func(context.Context) ([]byte, error)
  • RequestArgsFunc - Parse function arguments from HTTP requests
  • ResultsWriter - Write function results as HTTP responses

CLI Package (cli)

  • StringArgsDispatcher - Command dispatcher for CLI apps
  • SuperStringArgsDispatcher - Multi-level command dispatcher
  • CompleteStringArgsDispatcher / CompleteSuperStringArgsDispatcher - Shell completion support

HTML Forms (go-htmlform)

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.

Code Generator (cmd/gen-func-wrappers)

  • Generates optimized wrapper code
  • Zero reflection overhead
  • Preserves type safety
  • Supports custom import prefixes
  • Documentation: cmd/gen-func-wrappers/README.md

Configuration

String Scanners

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 = nil

But 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.UTC

HTTP Configuration

import (
    "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

Advanced Examples

Custom Result Handler

// 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)

Multi-level CLI Commands

// 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)
}

Testing

The library includes comprehensive tests. Run the tests of all modules of the workspace with:

./test-workspace.sh

go test ./... in the repository root only tests the root module.

Contributing

Contributions are welcome! Please:

  1. Add tests for new features
  2. Update documentation
  3. Follow existing code style
  4. Ensure ./test-workspace.sh passes

License

MIT License - see LICENSE file for details

Related Projects

  • go-types - Type definitions with string scanning support
  • go-astvisit - AST manipulation utilities used by the code generator

About

Wrapping Go functions as HTTP handlers and CLI commands

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages