blob: 1b0ecaca9c15c64134cf64afcf1cb570985bd706 [file] [log] [blame]
Scott Bakereee8dd82019-09-24 12:52:34 -07001// Copyright (c) 2016 Uber Technologies, Inc.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in
11// all copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19// THE SOFTWARE.
20
21package zap
22
23import (
24 "encoding/json"
25 "fmt"
26 "net/http"
27
28 "go.uber.org/zap/zapcore"
29)
30
31// ServeHTTP is a simple JSON endpoint that can report on or change the current
32// logging level.
33//
34// GET requests return a JSON description of the current logging level. PUT
35// requests change the logging level and expect a payload like:
36// {"level":"info"}
37//
38// It's perfectly safe to change the logging level while a program is running.
39func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
40 type errorResponse struct {
41 Error string `json:"error"`
42 }
43 type payload struct {
44 Level *zapcore.Level `json:"level"`
45 }
46
47 enc := json.NewEncoder(w)
48
49 switch r.Method {
50
51 case http.MethodGet:
52 current := lvl.Level()
53 enc.Encode(payload{Level: &current})
54
55 case http.MethodPut:
56 var req payload
57
58 if errmess := func() string {
59 if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
60 return fmt.Sprintf("Request body must be well-formed JSON: %v", err)
61 }
62 if req.Level == nil {
63 return "Must specify a logging level."
64 }
65 return ""
66 }(); errmess != "" {
67 w.WriteHeader(http.StatusBadRequest)
68 enc.Encode(errorResponse{Error: errmess})
69 return
70 }
71
72 lvl.SetLevel(*req.Level)
73 enc.Encode(req)
74
75 default:
76 w.WriteHeader(http.StatusMethodNotAllowed)
77 enc.Encode(errorResponse{
78 Error: "Only GET and PUT are supported.",
79 })
80 }
81}