github.com/kyma-project/kyma-environment-broker@v0.0.1/internal/httputil/response.go (about)

     1  package httputil
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/sirupsen/logrus"
     8  )
     9  
    10  // Writer provides syntactic sugar for writing http responses.
    11  // Works in two modes:
    12  //   - devMode: true - returns a given error in the response under `details` field
    13  //   - devMode: false - only log the given error in context of the requestID but do not return it in response
    14  type Writer struct {
    15  	log     logrus.FieldLogger
    16  	devMode bool
    17  }
    18  
    19  // NewResponseWriter returns new instance of Writer
    20  func NewResponseWriter(log logrus.FieldLogger, devMode bool) *Writer {
    21  	return &Writer{
    22  		log:     log,
    23  		devMode: devMode,
    24  	}
    25  }
    26  
    27  // NotFound writes standard NotFound response to given ResponseWriter.
    28  func (w *Writer) NotFound(rw http.ResponseWriter, r *http.Request, err error, context string) {
    29  	w.writeError(rw, r, ErrorDTO{
    30  		Status:  http.StatusNotFound,
    31  		Message: "Whoops! We can't find what you're looking for. Please try again.",
    32  		Details: fmt.Sprintf("%s: %s", context, err),
    33  	})
    34  }
    35  
    36  // InternalServerError writes standard InternalServerError response to given ResponseWriter.
    37  func (w *Writer) InternalServerError(rw http.ResponseWriter, r *http.Request, err error, context string) {
    38  	w.writeError(rw, r, ErrorDTO{
    39  		Status:  http.StatusInternalServerError,
    40  		Message: "Something went very wrong. Please try again.",
    41  		Details: fmt.Sprintf("%s: %s", context, err),
    42  	})
    43  }
    44  
    45  func (w *Writer) writeError(rw http.ResponseWriter, r *http.Request, errDTO ErrorDTO) {
    46  	errDTO.RequestID = r.Header.Get("X-Request-Id")
    47  	if !w.devMode {
    48  		w.log.WithField("request-id", errDTO.RequestID).Error(errDTO.Details)
    49  		errDTO.Details = ""
    50  	}
    51  
    52  	if err := JSONEncodeWithCode(rw, errDTO, errDTO.Status); err != nil {
    53  		w.log.WithField("request-id", errDTO.RequestID).Errorf("while encoding error DTO: %s", err)
    54  		rw.WriteHeader(http.StatusInternalServerError)
    55  		return
    56  	}
    57  }