reflectx

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 11, 2024 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrIncorrectArgumentCount = errors.New("incorrect number of arguments")
	ErrInvalidArgumentValue   = errors.New("invalid argument value")
	ErrMethodNotFound         = errors.New("method not found")
)

Error types.

View Source
var (
	// ErrMethodAlreadyDefined is returned when a method has already been defined in the router.
	ErrMethodAlreadyDefined = errors.New("pure method has already defined")

	// ErrUnsupportedMethod is returned when a method is not supported by the router.
	ErrUnsupportedMethod = errors.New("unsupported method")

	// ErrInvalidMethodName is returned when a method has an invalid name.
	ErrInvalidMethodName = errors.New("invalid method name")
)

Functions

func Call

func Call(v any, method string, args ...string) ([]any, error)

Call invokes a specified method on a given value using reflection. The method to be invoked is identified by its name. It checks whether the specified method exists on the value 'v' and if the number of provided arguments matches the method's expected input parameters. If the method is found and the arguments match, it attempts to convert the string arguments into the method's expected argument types using various unmarshalers or decoders, such as JSON, proto.Message, encoding.TextUnmarshaler, encoding.BinaryUnmarshaler, and gob.GobDecoder.

The process follows these steps:

  1. Check if the input string arguments are valid JSON; if so, attempt to unmarshal into the expected types.
  2. If not valid JSON, attempt to decode the string using the aforementioned interfaces in sequential order based on the type compatibility.
  3. Call the method with the prepared arguments and capture the output.

The function returns a slice of any type representing the output from the called method, and an error if the method is not found, the number of arguments does not match, or if an error occurs during argument conversion or method invocation.

Parameters:

  • v: The value on which the method is to be invoked.
  • method: The name of the method to invoke.
  • args: A slice of strings representing the arguments for the method.

Returns:

  • []any: A slice containing the outputs of the method, or nil if an error occurs.
  • error: An error if the method is not found, the number of arguments is incorrect, or any other issue during invocation.

Example:

type MyType struct {
    Data string
}

func (m *MyType) Update(data string) string {
    m.Data = data
    return fmt.Sprintf("Updated data to: %s", m.Data)
}

func main() {
    myInstance := &MyType{}
    output, err := Call(myInstance, "Update", `"New data"`)
    if err != nil {
        log.Fatalf("Error invoking method: %v", err)
    }
    fmt.Println(output[0]) // Output: Updated data to: New data
}

func IsArgOfType

func IsArgOfType(v any, method string, i int, argType any) bool

IsArgOfType checks if the i-th argument of the specified method on value 'v' is of the given type 'argType'.

Parameters:

  • v: The value whose method's argument is to be checked.
  • method: The name of the method to inspect.
  • i: The index of the argument to check (0-based).
  • argType: An example value of the desired type.

Returns:

  • bool: True if the i-th argument is of the specified type, false otherwise.

func MethodParamCounts

func MethodParamCounts(v any, method string) (in int, out int)

MethodParamCounts inspects the type of the given value 'v' and returns the number of input and output parameters of the specified method using reflection. If the method does not exist, it returns -1 for both values.

Parameters:

  • v: The value whose method's parameters are to be inspected.
  • method: The name of the method to inspect.

Returns:

  • int: The number of input parameters of the method.
  • int: The number of output parameters of the method.

func MethodReturnsError

func MethodReturnsError(v any, method string) bool

MethodReturnsError checks if the last return value of the specified method on value 'v' is of type error.

Parameters:

  • v: The value whose method's return value is to be checked.
  • method: The name of the method to inspect.

Returns:

  • bool: True if the last return value is of type error, false otherwise.

func Methods

func Methods(v any) []string

Methods inspects the type of the given value 'v' using reflection and returns a slice of strings containing the names of all methods that are defined on its type. This function only considers exported methods (those starting with an uppercase letter) due to Go's visibility rules in reflection.

Parameters:

  • v: The value whose type's methods are to be listed.

Returns:

  • []string: A slice containing the names of all methods associated with the type of 'v'.

func ValidateArguments

func ValidateArguments(v any, method string, stub shim.ChaincodeStubInterface, args ...string) error

ValidateArguments validates the arguments for the specified method on the given value using reflection. It checks whether the specified method exists on the value 'v' and if the number of provided arguments matches the method's expected input parameters. Additionally, it attempts to convert the string arguments into the expected types using various unmarshaling or decoding interfaces such as JSON, proto.Message, encoding.TextUnmarshaler, encoding.BinaryUnmarshaler. If an argument implements the Validator or ValidatorWithStub interfaces, its Validate method is called (with the provided stub if available).

The function returns an error if the method is not found, the number of arguments is incorrect, or if an error occurs during argument conversion or validation.

Parameters:

  • v: The value on which the method is to be validated.
  • method: The name of the method to validate.
  • stub: The ChaincodeStubInterface used for access control checks (optional).
  • args: A slice of strings representing the arguments for the method.

Returns:

  • error: An error if the method is not found, the number of arguments is incorrect, or any other issue during validation.

Types

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router routes method calls to contract methods based on reflection.

func NewRouter

func NewRouter(baseContract contract.Base, cfg RouterConfig) (*Router, error)

NewRouter creates a new ReflectRouter instance with the given contract and configuration. It reflects on the methods of the provided contract and sets up routing for them, respecting the configuration options specified.

Parameters:

  • baseContract: The contract instance to route methods for.
  • cfg: Configuration options for the router.

Returns:

  • *ReflectRouter: A new ReflectRouter instance.
  • error: An error if the router setup fails.

func (*Router) Check

func (r *Router) Check(method string, args ...string) error

Check validates the provided arguments for the specified method. It returns an error if the validation fails.

Parameters:

  • method: The name of the method to validate arguments for.
  • args: The arguments to validate.

Returns:

  • error: An error if the validation fails.

func (*Router) Invoke

func (r *Router) Invoke(method string, args ...string) ([]any, error)

Invoke calls the specified method with the provided arguments. It returns a slice of return values and an error if the invocation fails.

Parameters:

  • method: The name of the method to invoke.
  • args: The arguments to pass to the method.

Returns:

  • []any: A slice of return values from the method.
  • error: An error if the invocation fails.

func (*Router) Methods

func (r *Router) Methods() map[contract.Function]contract.Method

Methods retrieves a map of all available methods, keyed by their chaincode function names.

Returns:

  • map[contract.Function]contract.Method: A map of all available methods.

type RouterConfig

type RouterConfig struct {
	SwapsDisabled      bool     // Indicates if swap methods should be disabled.
	MultiSwapsDisabled bool     // Indicates if multi-swap methods should be disabled.
	DisabledMethods    []string // List of methods that should be disabled.
}

RouterConfig holds configuration options for the ReflectRouter.

type Validator

type Validator interface {
	Validate() error
}

Validator is an interface that can be implemented by types that can validate themselves.

type ValidatorWithStub

type ValidatorWithStub interface {
	ValidateWithStub(stub shim.ChaincodeStubInterface) error
}

ValidatorWithStub is an interface that can be implemented by types that can validate themselves.

Jump to

Keyboard shortcuts

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