github.com/blong14/gache@v0.0.0-20240124023949-89416fd8bbfa/client/conn.go (about) 1 package client 2 3 import ( 4 "context" 5 "errors" 6 7 gdb "github.com/blong14/gache/internal/db" 8 gproxy "github.com/blong14/gache/internal/proxy" 9 ) 10 11 type Client interface { 12 Close(ctx context.Context) error 13 Get(ctx context.Context, t, k []byte) ([]byte, error) 14 Set(ctx context.Context, t, k, v []byte) error 15 } 16 17 // proxyClient implements Client 18 type proxyClient struct { 19 proxy *gproxy.QueryProxy 20 } 21 22 func NewProxyClient() Client { 23 proxy, err := gproxy.NewQueryProxy() 24 if err != nil { 25 panic(err) 26 } 27 gproxy.StartProxy(context.Background(), proxy) 28 return &proxyClient{proxy: proxy} 29 } 30 31 func (c *proxyClient) Get(ctx context.Context, table, key []byte) ([]byte, error) { 32 query, _ := gdb.NewGetValueQuery(ctx, table, key) 33 c.proxy.Send(ctx, query) 34 resp := query.GetResponse() 35 if !resp.Success { 36 return nil, errors.New("missing value") 37 } 38 return resp.Value, nil 39 } 40 41 func (c *proxyClient) Set(ctx context.Context, table, key, value []byte) error { 42 query, _ := gdb.NewSetValueQuery(ctx, table, key, value) 43 c.proxy.Send(ctx, query) 44 resp := query.GetResponse() 45 if !resp.Success { 46 return errors.New("key not set") 47 } 48 return nil 49 } 50 51 func (c *proxyClient) Close(ctx context.Context) error { 52 gproxy.StopProxy(ctx, c.proxy) 53 return nil 54 } 55