Path: blob/main/vendor/go.uber.org/zap/http_handler.go
2872 views
// Copyright (c) 2016 Uber Technologies, Inc.1//2// Permission is hereby granted, free of charge, to any person obtaining a copy3// of this software and associated documentation files (the "Software"), to deal4// in the Software without restriction, including without limitation the rights5// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell6// copies of the Software, and to permit persons to whom the Software is7// furnished to do so, subject to the following conditions:8//9// The above copyright notice and this permission notice shall be included in10// all copies or substantial portions of the Software.11//12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR13// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,14// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE15// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER16// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,17// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN18// THE SOFTWARE.1920package zap2122import (23"encoding/json"24"errors"25"fmt"26"io"27"net/http"2829"go.uber.org/zap/zapcore"30)3132// ServeHTTP is a simple JSON endpoint that can report on or change the current33// logging level.34//35// # GET36//37// The GET request returns a JSON description of the current logging level like:38//39// {"level":"info"}40//41// # PUT42//43// The PUT request changes the logging level. It is perfectly safe to change the44// logging level while a program is running. Two content types are supported:45//46// Content-Type: application/x-www-form-urlencoded47//48// With this content type, the level can be provided through the request body or49// a query parameter. The log level is URL encoded like:50//51// level=debug52//53// The request body takes precedence over the query parameter, if both are54// specified.55//56// This content type is the default for a curl PUT request. Following are two57// example curl requests that both set the logging level to debug.58//59// curl -X PUT localhost:8080/log/level?level=debug60// curl -X PUT localhost:8080/log/level -d level=debug61//62// For any other content type, the payload is expected to be JSON encoded and63// look like:64//65// {"level":"info"}66//67// An example curl request could look like this:68//69// curl -X PUT localhost:8080/log/level -H "Content-Type: application/json" -d '{"level":"debug"}'70func (lvl AtomicLevel) ServeHTTP(w http.ResponseWriter, r *http.Request) {71if err := lvl.serveHTTP(w, r); err != nil {72w.WriteHeader(http.StatusInternalServerError)73fmt.Fprintf(w, "internal error: %v", err)74}75}7677func (lvl AtomicLevel) serveHTTP(w http.ResponseWriter, r *http.Request) error {78type errorResponse struct {79Error string `json:"error"`80}81type payload struct {82Level zapcore.Level `json:"level"`83}8485enc := json.NewEncoder(w)8687switch r.Method {88case http.MethodGet:89return enc.Encode(payload{Level: lvl.Level()})9091case http.MethodPut:92requestedLvl, err := decodePutRequest(r.Header.Get("Content-Type"), r)93if err != nil {94w.WriteHeader(http.StatusBadRequest)95return enc.Encode(errorResponse{Error: err.Error()})96}97lvl.SetLevel(requestedLvl)98return enc.Encode(payload{Level: lvl.Level()})99100default:101w.WriteHeader(http.StatusMethodNotAllowed)102return enc.Encode(errorResponse{103Error: "Only GET and PUT are supported.",104})105}106}107108// Decodes incoming PUT requests and returns the requested logging level.109func decodePutRequest(contentType string, r *http.Request) (zapcore.Level, error) {110if contentType == "application/x-www-form-urlencoded" {111return decodePutURL(r)112}113return decodePutJSON(r.Body)114}115116func decodePutURL(r *http.Request) (zapcore.Level, error) {117lvl := r.FormValue("level")118if lvl == "" {119return 0, errors.New("must specify logging level")120}121var l zapcore.Level122if err := l.UnmarshalText([]byte(lvl)); err != nil {123return 0, err124}125return l, nil126}127128func decodePutJSON(body io.Reader) (zapcore.Level, error) {129var pld struct {130Level *zapcore.Level `json:"level"`131}132if err := json.NewDecoder(body).Decode(&pld); err != nil {133return 0, fmt.Errorf("malformed request body: %v", err)134}135if pld.Level == nil {136return 0, errors.New("must specify logging level")137}138return *pld.Level, nil139}140141142