-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathhandlers.go
66 lines (54 loc) · 1.69 KB
/
handlers.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package main
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/gin-gonic/gin"
)
type Handlers struct {
database *Database
vault *Vault
secureServiceAddress string
}
// (POST /payments) : demonstrates fetching a static secret from Vault and using it to talk to another service
func (h *Handlers) CreatePayment(c *gin.Context) {
// retrieve the secret from Vault
apiKey, err := h.vault.GetSecretAPIKey(c.Request.Context())
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
request, err := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, h.secureServiceAddress, nil)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
return
}
// use the api key in our request header
request.Header.Set("X-API-KEY", apiKey)
response, err := http.DefaultClient.Do(request)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
defer func() {
_ = response.Body.Close()
}()
// forward the response back to the caller
b, err := ioutil.ReadAll(response.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("could not read secure service response body: %v", err)})
return
}
c.Data(response.StatusCode, "application/json", b)
}
// (GET /products) : demonstrates database authentication with dynamic secrets
func (h *Handlers) GetProducts(c *gin.Context) {
products, err := h.database.GetProducts(c.Request.Context())
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, products)
}