Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Dynamic proxy for golang

License

NotificationsYou must be signed in to change notification settings

ovechkin-dm/go-dyno

Repository files navigation

Dynamic proxy for golang >= 1.18

An attempt to bring java-like dynamic proxy to golang.

You can use dynamic proxies for AOP, logging, caching, metrics and mocking.

Basic example of caching proxy:

package mainimport ("fmt""github.com/ovechkin-dm/go-dyno/pkg/dyno""reflect""time")typeServiceinterface {Foo(sstring)stringBar(iint)int}typeImplstruct {}func (h*Impl)Foo(sstring)string {time.Sleep(2*time.Second)returns+" world!"}func (h*Impl)Bar(iint)int {time.Sleep(2*time.Second)returni+1}typeCachingProxystruct {delegateinterface{}cachemap[string][]reflect.Value}func (c*CachingProxy)Handle(method reflect.Method,values []reflect.Value) []reflect.Value {_,ok:=c.cache[method.Name]ref:=reflect.ValueOf(c.delegate)if!ok {out:=ref.MethodByName(method.Name).Call(values)c.cache[method.Name]=out}returnc.cache[method.Name]}funcCreateCachingProxyFor[Tany](tT) (T,error) {proxy:=&CachingProxy{delegate:t,cache:make(map[string][]reflect.Value),}return dyno.Dynamic[T](proxy.Handle)}funcmain() {s:=&Impl{}proxy,err:=CreateCachingProxyFor[Service](s)iferr!=nil {panic(err)}fmt.Println(proxy.Foo("hello"))fmt.Println(proxy.Foo("hello"))fmt.Println(proxy.Foo("hello"))}

For golang <= 1.16 you can look at dpig project


[8]ページ先頭

©2009-2025 Movatter.jp