http_handler.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. // 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. package zap
  21. import (
  22. "encoding/json"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "net/http"
  27. "go.uber.org/zap/zapcore"
  28. )
  29. // ServeHTTP is a simple JSON endpoint that can report on or change the current
  30. // logging level.
  31. //
  32. // # GET
  33. //
  34. // The GET request returns a JSON description of the current logging level like:
  35. //
  36. // {"level":"info"}
  37. //
  38. // # PUT
  39. //
  40. // The PUT request changes the logging level. It is perfectly safe to change the
  41. // logging level while a program is running. Two content types are supported:
  42. //
  43. // Content-Type: application/x-www-form-urlencoded
  44. //
  45. // With this content type, the level can be provided through the request body or
  46. // a query parameter. The log level is URL encoded like:
  47. //
  48. // level=debug
  49. //
  50. // The request body takes precedence over the query parameter, if both are
  51. // specified.
  52. //
  53. // This content type is the default for a curl PUT request. Following are two
  54. // example curl requests that both set the logging level to debug.
  55. //
  56. // curl -X PUT localhost:8080/log/level?level=debug
  57. // curl -X PUT localhost:8080/log/level -d level=debug
  58. //
  59. // For any other content type, the payload is expected to be JSON encoded and
  60. // look like:
  61. //
  62. // {"level":"info"}
  63. //
  64. // An example curl request could look like this:
  65. //
  66. // curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}'
  67. func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  68. if err := lvl.serveHTTP(w, r); err != nil {
  69. w.WriteHeader(http.StatusInternalServerError)
  70. fmt.Fprintf(w, "internal error: %v", err)
  71. }
  72. }
  73. func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error {
  74. type errorResponse struct {
  75. Error string `json:"error"`
  76. }
  77. type payload struct {
  78. Level zapcore.Level `json:"level"`
  79. }
  80. enc := json.NewEncoder(w)
  81. switch r.Method {
  82. case http.MethodGet:
  83. return enc.Encode(payload{Level: lvl.Level()})
  84. case http.MethodPut:
  85. requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r)
  86. if err != nil {
  87. w.WriteHeader(http.StatusBadRequest)
  88. return enc.Encode(errorResponse{Error: err.Error()})
  89. }
  90. lvl.SetLevel(requestedLvl)
  91. return enc.Encode(payload{Level: lvl.Level()})
  92. default:
  93. w.WriteHeader(http.StatusMethodNotAllowed)
  94. return enc.Encode(errorResponse{
  95. Error: "Only GET and PUT are supported.",
  96. })
  97. }
  98. }
  99. // Decodes incoming PUT requests and returns the requested logging level.
  100. func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) {
  101. if contentType == "application/x-www-form-urlencoded" {
  102. return decodePutURL(r)
  103. }
  104. return decodePutJSON(r.Body)
  105. }
  106. func decodePutURL(r *http.Request) (zapcore.Level, error) {
  107. lvl := r.FormValue("level")
  108. if lvl == "" {
  109. return 0, errors.New("must specify logging level")
  110. }
  111. var l zapcore.Level
  112. if err := l.UnmarshalText([]byte(lvl)); err != nil {
  113. return 0, err
  114. }
  115. return l, nil
  116. }
  117. func decodePutJSON(body io.Reader) (zapcore.Level, error) {
  118. var pld struct {
  119. Level *zapcore.Level `json:"level"`
  120. }
  121. if err := json.NewDecoder(body).Decode(&pld); err != nil {
  122. return 0, fmt.Errorf("malformed request body: %v", err)
  123. }
  124. if pld.Level == nil {
  125. return 0, errors.New("must specify logging level")
  126. }
  127. return *pld.Level, nil
  128. }