1
0
Fork 0
mirror of https://github.com/portainer/portainer.git synced 2025-07-24 07:49:41 +02:00

feat(libhttp): move into the Portainer repository EE-5475 (#10231)

This commit is contained in:
andres-portainer 2023-09-01 19:27:02 -03:00 committed by GitHub
parent 090fa4aeb3
commit 8cc5e0796c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
249 changed files with 1059 additions and 639 deletions

View file

@ -0,0 +1,45 @@
// Package response provides convenience functions to write into a http.ResponseWriter.
package response
import (
"encoding/json"
"errors"
"fmt"
"net/http"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
)
// JSON encodes data to rw in JSON format. Returns a pointer to a
// HandlerError if encoding fails.
func JSON(rw http.ResponseWriter, data interface{}) *httperror.HandlerError {
rw.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(rw).Encode(data)
if err != nil {
return httperror.InternalServerError("Unable to write JSON response", err)
}
return nil
}
// JSON encodes data to rw in YAML format. Returns a pointer to a
// HandlerError if encoding fails.
func YAML(rw http.ResponseWriter, data interface{}) *httperror.HandlerError {
rw.Header().Set("Content-Type", "text/yaml")
strData, ok := data.(string)
if !ok {
return httperror.InternalServerError("Unable to write YAML response", errors.New("failed to convert input to string"))
}
fmt.Fprint(rw, strData)
return nil
}
// Empty merely sets the response code to NoContent (204).
func Empty(rw http.ResponseWriter) *httperror.HandlerError {
rw.WriteHeader(http.StatusNoContent)
return nil
}