-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapi.go
119 lines (95 loc) · 2.3 KB
/
api.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package http
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
routing "github.com/qiangxue/fasthttp-routing"
"github.com/valyala/fasthttp"
)
const (
applicationPort = 5000
daprSecretURL = "http://localhost:3500/v1.0/secrets"
secretStoreName = "azurekeyvault"
secretOne = "secretone"
secretTwo = "secretTwo"
)
// API interface
type API interface {
StartNonBlocking()
}
type api struct {
router *routing.Router
port int
}
// NewAPI creates a new server instance
func NewAPI() API {
api := &api{
port: applicationPort,
router: routing.New(),
}
api.router.Get("/secret", api.onGetSecrets)
return api
}
func (s *api) StartNonBlocking() {
go func() {
err := fasthttp.ListenAndServe(fmt.Sprintf(":%v", s.port), s.router.HandleRequest)
if err != nil {
log.Println(err)
}
}()
}
func (s *api) onGetSecrets(c *routing.Context) error {
baseURL := fmt.Sprintf("%s/%s", daprSecretURL, secretStoreName)
secretOneURL := fmt.Sprintf("%s/%s", baseURL, secretOne)
secretTwoURL := fmt.Sprintf("%s/%s", baseURL, secretTwo)
// query first value
resp, err := http.Get(secretOneURL)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
tmp := make(map[string]string)
err = json.Unmarshal(body, &tmp)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
vauleOne := tmp[secretOne]
// query second value
resp2, err := http.Get(secretTwoURL)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
defer resp2.Body.Close()
body2, err := ioutil.ReadAll(resp2.Body)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
tmp = make(map[string]string)
err = json.Unmarshal(body2, &tmp)
if err != nil {
c.Response.SetStatusCode(500)
c.Response.SetBody([]byte(err.Error()))
return err
}
vauleTwo := tmp[secretTwo]
result := fmt.Sprintf("Result from Go API: secretOne %s | secretTwo: %s", vauleOne, vauleTwo)
c.Response.SetStatusCode(200)
c.Response.SetBody([]byte(result))
return nil
}