WIP: initial commit
This commit is contained in:
72
agent/agent.go
Normal file
72
agent/agent.go
Normal file
@@ -0,0 +1,72 @@
|
||||
package agent
|
||||
|
||||
/*
|
||||
Copyright 2025 Suyono <suyono3484@gmail.com>
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
|
||||
pb "gitea.suyono.dev/suyono/go-agent/proto"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
)
|
||||
|
||||
type CacheConn struct {
|
||||
conn *grpc.ClientConn
|
||||
client pb.AgentClient
|
||||
}
|
||||
|
||||
func NewCacheConn(socketPath string) (CacheConn, error) {
|
||||
var (
|
||||
result CacheConn
|
||||
err error
|
||||
)
|
||||
|
||||
result.conn, err = grpc.NewClient(
|
||||
socketPath,
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, addr string) (net.Conn, error) {
|
||||
var d net.Dialer
|
||||
return d.DialContext(ctx, "unix", addr)
|
||||
}),
|
||||
)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
result.client = pb.NewAgentClient(result.conn)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (c CacheConn) Get(ctx context.Context, key string) (string, error) {
|
||||
var (
|
||||
rpcResult *pb.CacheValue
|
||||
err error
|
||||
)
|
||||
|
||||
if rpcResult, err = c.client.Get(ctx, &pb.CacheGetRequest{Key: key}); err != nil {
|
||||
return "", fmt.Errorf("get from cache: %w", err)
|
||||
}
|
||||
|
||||
if rpcResult.Status != "OK" {
|
||||
return "", fmt.Errorf("get from cache: status %s with message %s", rpcResult.Status, rpcResult.Message)
|
||||
}
|
||||
|
||||
return rpcResult.Value, nil
|
||||
}
|
||||
Reference in New Issue
Block a user