/
handler.go
73 lines (58 loc) · 1.62 KB
/
handler.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
package http
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gemcdaniel/aws-courier"
"github.com/gorilla/mux"
)
// Handler provides the routing for the API using the CredentialsService
type Handler struct {
*mux.Router
credentialsService awscourier.CredentialsService
}
// NewHandler initializes a new Handler
func NewHandler() *Handler {
h := &Handler{
Router: mux.NewRouter(),
}
h.HandleFunc("/aws_keys/{profile}", h.handleCredentials).Methods(http.MethodGet)
return h
}
// CredentialsService sets the CredentialsService for the Handler
func (h *Handler) CredentialsService(credentialsService awscourier.CredentialsService) {
h.credentialsService = credentialsService
}
func (h *Handler) handleCredentials(w http.ResponseWriter, r *http.Request) {
profile, ok := mux.Vars(r)["profile"]
if !ok {
writeError(http.StatusBadRequest, fmt.Errorf("no profile provided"), w)
return
}
credentials, err := h.credentialsService.Credentials(&profile)
if err != nil {
writeError(http.StatusInternalServerError, err, w)
return
}
data, err := json.Marshal(credentials)
if err != nil {
writeError(http.StatusInternalServerError, err, w)
return
}
writeResponse(http.StatusOK, data, w)
}
func writeError(code int, err error, w http.ResponseWriter) {
b, e := json.Marshal(err)
if e != nil {
writeResponse(http.StatusInternalServerError, []byte("{\"Message\":\"failed to marshal error\"}"), w)
return
}
writeResponse(code, b, w)
}
func writeResponse(code int, data []byte, w http.ResponseWriter) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(code)
if data != nil {
w.Write(data)
}
}