-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
91 lines (69 loc) · 1.87 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package gocache
import (
"context"
"fmt"
"google.golang.org/grpc"
"net"
"time"
)
var cache *Cache
type ServerConfig struct {
Port string
CachePtr *Cache
}
type Server struct {
}
func (s *Server) GetCache(ctx context.Context, request *GetCacheRequest) (*GetCacheResponse, error) {
cache, success := cache.Get(request.Key)
if !success {
return nil, NewError(404, fmt.Sprintf("can not get cache with key:%s", request.Key))
}
response := &GetCacheResponse{
Value: cache.([]byte),
Success: success,
}
return response, nil
}
func (s *Server) SaveCache(ctx context.Context, request *SaveCacheRequest) (*Empty, error) {
success, message := cache.Add(request.Key, request.Value, time.Second*time.Duration(request.Life))
if !success {
return nil, NewError(409, fmt.Sprintf("can not save e:%s", message))
}
return &Empty{}, nil
}
func (s *Server) DeleteCachedItem(ctx context.Context, request *DeleteCacheItemRequest) (*Empty, error) {
cache.DeleteCachedItem(request.Key)
return &Empty{}, nil
}
func (s *Server) ClearCache(ctx context.Context, request *Empty) (*Empty, error) {
cache.ClearCache()
return &Empty{}, nil
}
func validateServerConfig(config ServerConfig) (bool, *Error) {
if config.CachePtr == nil {
return false, NewError(400, "you should add cache instance")
}
if config.Port == "" {
return false, NewError(400, "port should not be empty")
}
return true, nil
}
func NewCacheServer(config ServerConfig) *Error {
valid, validationErr := validateServerConfig(config)
if !valid {
return validationErr
}
cache = config.CachePtr
address := "0.0.0.0:" + config.Port
listen, err := net.Listen("tcp", address)
if err != nil {
return NewError(500, err.Error())
}
s := grpc.NewServer()
RegisterCacheServiceServer(s, &Server{})
serveError := s.Serve(listen)
if serveError != nil {
return NewError(500, serveError.Error())
}
return nil
}