-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
spec.go
82 lines (65 loc) · 1.79 KB
/
spec.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
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package httpadmin
import (
"encoding/json"
"fmt"
"net/http"
"github.com/hyperledger/fabric/common/flogging"
)
//go:generate counterfeiter -o fakes/logging.go -fake-name Logging . Logging
type Logging interface {
ActivateSpec(spec string) error
Spec() string
}
type LogSpec struct {
Spec string `json:"spec,omitempty"`
}
type ErrorResponse struct {
Error string `json:"error"`
}
func NewSpecHandler() *SpecHandler {
return &SpecHandler{
Logging: flogging.Global,
Logger: flogging.MustGetLogger("flogging.httpadmin"),
}
}
type SpecHandler struct {
Logging Logging
Logger *flogging.FabricLogger
}
func (h *SpecHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
switch req.Method {
case http.MethodPut:
var logSpec LogSpec
decoder := json.NewDecoder(req.Body)
if err := decoder.Decode(&logSpec); err != nil {
h.sendResponse(resp, http.StatusBadRequest, err)
return
}
req.Body.Close()
if err := h.Logging.ActivateSpec(logSpec.Spec); err != nil {
h.sendResponse(resp, http.StatusBadRequest, err)
return
}
resp.WriteHeader(http.StatusNoContent)
case http.MethodGet:
h.sendResponse(resp, http.StatusOK, &LogSpec{Spec: h.Logging.Spec()})
default:
err := fmt.Errorf("invalid request method: %s", req.Method)
h.sendResponse(resp, http.StatusBadRequest, err)
}
}
func (h *SpecHandler) sendResponse(resp http.ResponseWriter, code int, payload interface{}) {
encoder := json.NewEncoder(resp)
if err, ok := payload.(error); ok {
payload = &ErrorResponse{Error: err.Error()}
}
resp.WriteHeader(code)
resp.Header().Set("Content-Type", "application/json")
if err := encoder.Encode(payload); err != nil {
h.Logger.Errorw("failed to encode payload", "error", err)
}
}