github.com/yacovm/fabric@v2.0.0-alpha.0.20191128145320-c5d4087dc723+incompatible/common/flogging/httpadmin/spec.go (about) 1 /* 2 Copyright IBM Corp. All Rights Reserved. 3 4 SPDX-License-Identifier: Apache-2.0 5 */ 6 7 package httpadmin 8 9 import ( 10 "encoding/json" 11 "fmt" 12 "net/http" 13 14 "github.com/hyperledger/fabric/common/flogging" 15 ) 16 17 //go:generate counterfeiter -o fakes/logging.go -fake-name Logging . Logging 18 19 type Logging interface { 20 ActivateSpec(spec string) error 21 Spec() string 22 } 23 24 type LogSpec struct { 25 Spec string `json:"spec,omitempty"` 26 } 27 28 type ErrorResponse struct { 29 Error string `json:"error"` 30 } 31 32 func NewSpecHandler() *SpecHandler { 33 return &SpecHandler{ 34 Logging: flogging.Global, 35 Logger: flogging.MustGetLogger("flogging.httpadmin"), 36 } 37 } 38 39 type SpecHandler struct { 40 Logging Logging 41 Logger *flogging.FabricLogger 42 } 43 44 func (h *SpecHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { 45 switch req.Method { 46 case http.MethodPut: 47 var logSpec LogSpec 48 decoder := json.NewDecoder(req.Body) 49 if err := decoder.Decode(&logSpec); err != nil { 50 h.sendResponse(resp, http.StatusBadRequest, err) 51 return 52 } 53 req.Body.Close() 54 55 if err := h.Logging.ActivateSpec(logSpec.Spec); err != nil { 56 h.sendResponse(resp, http.StatusBadRequest, err) 57 return 58 } 59 resp.WriteHeader(http.StatusNoContent) 60 61 case http.MethodGet: 62 h.sendResponse(resp, http.StatusOK, &LogSpec{Spec: h.Logging.Spec()}) 63 64 default: 65 err := fmt.Errorf("invalid request method: %s", req.Method) 66 h.sendResponse(resp, http.StatusBadRequest, err) 67 } 68 } 69 70 func (h *SpecHandler) sendResponse(resp http.ResponseWriter, code int, payload interface{}) { 71 encoder := json.NewEncoder(resp) 72 if err, ok := payload.(error); ok { 73 payload = &ErrorResponse{Error: err.Error()} 74 } 75 76 resp.WriteHeader(code) 77 78 resp.Header().Set("Content-Type", "application/json") 79 if err := encoder.Encode(payload); err != nil { 80 h.Logger.Errorw("failed to encode payload", "error", err) 81 } 82 }