/
repository.go
95 lines (79 loc) · 1.98 KB
/
repository.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
92
93
94
95
package hive_go
import (
"fmt"
"github.com/patrickmn/go-cache"
uuid "github.com/satori/go.uuid"
"google.golang.org/protobuf/proto"
"io/ioutil"
"net/http"
"time"
)
type SecretsRepository interface {
GetSecret(id uuid.UUID) *Secret
}
type Repository struct {
client *http.Client
hiveAPI string
cache *cache.Cache
}
func InitRepository(hiveAPI string) *Repository {
return &Repository{client: &http.Client{}, hiveAPI: hiveAPI, cache: cache.New(time.Minute*10, time.Minute*5)}
}
func (repository Repository) getFullURL(path string) string {
return fmt.Sprintf("%s/%s", repository.hiveAPI, path)
}
func (repository Repository) getSecretsURL(id uuid.UUID) string {
return repository.getFullURL(fmt.Sprintf("api/v1/secrets/%s", id.String()))
}
func (repository Repository) getSecret(id uuid.UUID) *Secret {
if x, found := repository.cache.Get(id.String()); found {
if secret, ok := x.(*Secret); ok {
return secret
}
}
return nil
}
func (repository Repository) SetSecret(secret *Secret) {
repository.cache.Set(secret.Id.String(), secret, time.Hour*24)
}
func (repository Repository) GetSecret(id uuid.UUID) *Secret {
secret := repository.getSecret(id)
if secret != nil {
return secret
}
url := repository.getSecretsURL(id)
request, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil
}
request.Header.Add("Content-Type", "application/octet-stream")
resp, err := repository.client.Do(request)
if err != nil {
return nil
}
if resp.StatusCode != 200 {
return nil
}
var response GetSecretResponseV1
body, err := ioutil.ReadAll(resp.Body)
err = proto.Unmarshal(body, &response)
if err != nil {
return nil
}
secretData := response.Data
uuidID, err := uuid.FromBytes(secretData.Id)
if err != nil {
return nil
}
uuidValue, err := uuid.FromBytes(secretData.Value)
if err != nil {
return nil
}
secret = &Secret{
Id: uuidID,
Created: secretData.Created,
Value: uuidValue,
}
repository.SetSecret(secret)
return secret
}