Skip to content

Instantly share code, notes, and snippets.

@azmanabdlh
Last active January 30, 2024 06:23
Show Gist options
  • Save azmanabdlh/7bcae0770e52fc9a07d1bbfc730b01ac to your computer and use it in GitHub Desktop.
Save azmanabdlh/7bcae0770e52fc9a07d1bbfc730b01ac to your computer and use it in GitHub Desktop.
new callwrapper
package main
import "fmt"
func main() {
cw := NewCallWrapper()
var dataStruct string
cw.SetOptions(
WithRedis("redis", 1000, dataStruct),
WithArrRedis([]string{"12", "13"}, 1000, dataStruct),
).Call(func() (interface{}, error) {
fmt.Println("actual func...")
return nil, nil
})
fmt.Println("done...")
// output:
// get key ==> redis
// get index: 0 key: 12 ==>
// get index: 1 key: 13 ==>
// actual func...
// done...
}
type Redis struct {
key string
keys []string
}
type PublishMetric struct {
key string
}
func WithArrRedis(keys []string, ttl int, dataStruct interface{}) *Redis {
return &Redis{keys: keys}
}
func WithRedis(key string, ttl int, dataStruct interface{}) *Redis {
return &Redis{key: key}
}
func (r *Redis) Before() (interface{}, error) {
if len(r.keys) == 0 {
fmt.Println("get key ==> ", r.key)
}
for idx, key := range r.keys {
fmt.Printf("get index: %d key: %s ==> \n", idx, key)
}
return nil, nil
}
func WithPublishMetric(key string) *PublishMetric {
return &PublishMetric{key}
}
func (pub *PublishMetric) Before() (interface{}, error) {
fmt.Println("key ==> ", pub.key)
return nil, nil
}
func NewCallWrapper() *CallWrapper {
return &CallWrapper{}
}
type CallWrapperOption interface {
Before() (interface{}, error)
}
type CallWrapper struct {
opts []CallWrapperOption
}
func (cw *CallWrapper) SetOptions(opts ...CallWrapperOption) *CallWrapper {
cw.opts = opts
return cw
}
func (cw *CallWrapper) Call(fn func() (interface{}, error)) (interface{}, error) {
for _, opt := range cw.opts {
opt.Before()
}
return fn()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment