fn

package
v0.0.0-...-607911e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 9, 2024 License: MIT Imports: 7 Imported by: 4

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ArgsTo

func ArgsTo(fntyp reflect.Type, args []any) ([]reflect.Value, error)

ArgsTo converts the arguments into `reflect.Value`s suitable to pass as parameters to a function with the given type via reflection.

func Call

func Call(fn any, args []any) (_ []any, err error)

Call wraps invoking a function via reflection, converting the arguments with ArgsTo and the returns with ParseReturn. fn argument can be a function or a reflect.Value for a function.

func HandlerFrom

func HandlerFrom[T any](v T) rpc.Handler

HandlerFrom uses reflection to return a handler from either a function or methods from a struct. When a struct is used, HandlerFrom creates a RespondMux registering each method as a handler using its method name. From there, methods are treated just like functions.

The registered methods can be limited by providing an interface type parameter:

h := HandlerFrom[interface{
	OnlyTheseMethods()
	WillBeRegistered()
}](myHandlerImplementation)

If a struct method matches the HandlerFunc signature, the method will be called directly with the handler arguments. Otherwise it will be wrapped as described below.

Function handlers expect an array to use as arguments. If the incoming argument array is too large or too small, the handler returns an error. Functions can opt-in to take a final Call pointer argument, allowing the handler to give it the Call value being processed. Functions can return nothing which the handler returns as nil, or a single value which can be an error, or two values where one value is an error. In the latter case, the value is returned if the error is nil, otherwise just the error is returned. Handlers based on functions that return more than two values will simply ignore the remaining values.

Structs that implement the Handler interface will be added as a catch-all handler along with their individual methods. This lets you implement dynamic methods.

func ParseReturn

func ParseReturn(ret []reflect.Value) ([]any, error)

ParseReturn splits the results of reflect.Call() into the values, and possibly an error. If the last value is a non-nil error, this will return `nil, err`. If the last value is a nil error it will be removed from the value list. Any remaining values will be converted and returned as `any` typed values.

Types

type Args

type Args []any

Args is the expected argument value for calls made to HandlerFrom handlers. Since it is just a slice of empty interface values, you can alternatively use more specific slice types ([]int{}, etc) if all arguments are of the same type.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL