github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/admin/response_writers.go (about)

     1  package admin
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  )
     8  
     9  // Helper functions for writing the response
    10  func writeMessage(w http.ResponseWriter, code int, format string, args ...interface{}) {
    11  	w.WriteHeader(code)
    12  
    13  	_, _ = fmt.Fprintf(w, format, args...)
    14  	_, _ = fmt.Fprintln(w)
    15  }
    16  
    17  func (ctrl *Controller) writeError(w http.ResponseWriter, code int, err error, msg string) {
    18  	ctrl.log.WithError(err).Error(msg)
    19  	writeMessage(w, code, "%s: %q", msg, err)
    20  }
    21  
    22  func (ctrl *Controller) writeResponseJSON(w http.ResponseWriter, res interface{}) {
    23  	w.Header().Set("Content-Type", "application/json")
    24  	if err := json.NewEncoder(w).Encode(res); err != nil {
    25  		ctrl.writeError(w, http.StatusInternalServerError, err, "encoding response body")
    26  	}
    27  }