agones.dev/agones@v1.53.0/pkg/util/https/https.go (about)

     1  // Copyright 2019 Google LLC All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package https provides HTTPS helpers.
    16  package https
    17  
    18  import (
    19  	"io"
    20  	"net/http"
    21  
    22  	"agones.dev/agones/pkg/util/runtime"
    23  	"github.com/pkg/errors"
    24  	"github.com/sirupsen/logrus"
    25  )
    26  
    27  // ErrorHandlerFunc is a http handler that can return an error
    28  // for standard logging and a 500 response
    29  type ErrorHandlerFunc func(http.ResponseWriter, *http.Request) error
    30  
    31  // FourZeroFour is the standard 404 handler.
    32  func FourZeroFour(logger *logrus.Entry, w http.ResponseWriter, r *http.Request) {
    33  	f := ErrorHTTPHandler(logger, func(_ http.ResponseWriter, _ *http.Request) error {
    34  		body, err := io.ReadAll(r.Body)
    35  		if err != nil {
    36  			return errors.Wrap(err, "error in default handler")
    37  		}
    38  		defer r.Body.Close() // nolint: errcheck
    39  
    40  		LogRequest(logger, r).WithField("body", string(body)).Warn("404")
    41  		http.NotFound(w, r)
    42  
    43  		return nil
    44  	})
    45  
    46  	f(w, r)
    47  }
    48  
    49  // ErrorHTTPHandler is a conversion function that sets up a http.StatusInternalServerError
    50  // if an error is returned
    51  func ErrorHTTPHandler(logger *logrus.Entry, f ErrorHandlerFunc) http.HandlerFunc {
    52  	return func(w http.ResponseWriter, r *http.Request) {
    53  		err := f(w, r)
    54  		if err != nil {
    55  			runtime.HandleError(LogRequest(logger, r), err)
    56  			http.Error(w, err.Error(), http.StatusInternalServerError)
    57  			return
    58  		}
    59  	}
    60  }
    61  
    62  // LogRequest logs all the JSON parsable fields in a request
    63  // as otherwise, the request is not marshable
    64  func LogRequest(logger *logrus.Entry, r *http.Request) *logrus.Entry {
    65  	return logger.WithField("method", r.Method).
    66  		WithField("url", r.URL).
    67  		WithField("host", r.Host).
    68  		WithField("headers", r.Header).
    69  		WithField("requestURI", r.RequestURI)
    70  }