go-dyno

module
v0.5.2 Latest Latest
Warning

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

Go to latest
Published: Apr 16, 2025 License: MIT

README

Go-dyno

Build Status Codecov Go Report Card Documentation Release License

Dynamic proxy for golang

Go-dyno is a lightweight and flexible library for Go, inspired by Java's dynamic proxy mechanism. It enables dynamic creation of proxy implementations for interfaces at runtime, allowing developers to intercept and customize method calls programmatically. This makes it a powerful tool for building dynamic behaviors and enhancing flexibility in Go applications.

Documentation

Latest documentation is available here

Quick start

Install latest version of the library using go get command:

go get -u github.com/ovechkin-dm/go-dyno

Example

This is an example of proxy that prints method name before any method invocation of the original instance.

package main

import (
	"fmt"
	"reflect"

	"github.com/ovechkin-dm/go-dyno/pkg/dyno"
)

type Greeter interface {
	Greet() string
	SayHello(name string) string
}

type SimpleGreeter struct {

}

func (g *SimpleGreeter) Greet() string {
	return "Hello!"
}

func (g *SimpleGreeter) SayHello(name string) string {
	return fmt.Sprintf("Hello, %s!", name)
}

type ProxyHandler[T any] struct {
	Impl T
}

func (p *ProxyHandler[T]) Handle(m reflect.Method, values []reflect.Value) []reflect.Value {
	fmt.Println("Method called:", m.Name)
	return reflect.ValueOf(p.Impl).MethodByName(m.Name).Call(values)	
}



func main() {	
	greeter := &SimpleGreeter{}
	proxyHandler := &ProxyHandler[Greeter]{Impl: greeter}
	dynamicGreeter, err := dyno.Dynamic[Greeter](proxyHandler.Handle)
	if err != nil {
		fmt.Println("Error creating dynamic greeter:", err)
		return
	}

	fmt.Println(dynamicGreeter.Greet())
	fmt.Println(dynamicGreeter.SayHello("World"))
}

Directories

Path Synopsis
cmd
generate command
pkg

Jump to

Keyboard shortcuts

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