drone/internal/api/render/render.go
2022-08-09 12:37:37 -07:00

89 lines
2.5 KiB
Go

// Copyright 2021 Harness Inc. All rights reserved.
// Use of this source code is governed by the Polyform Free Trial License
// that can be found in the LICENSE.md file for this repository.
package render
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
)
// indent the json-encoded API responses
var indent bool
func init() {
indent, _ = strconv.ParseBool(
os.Getenv("HTTP_JSON_INDENT"),
)
}
// ErrorCode writes the json-encoded error message to the response.
func ErrorCode(w http.ResponseWriter, err error, status int) {
JSON(w, &Error{Message: err.Error()}, status)
}
// InternalError writes the json-encoded error message to the response
// with a 500 internal server error.
func InternalError(w http.ResponseWriter, err error) {
ErrorCode(w, err, 500)
}
// InternalErrorf writes the json-encoded error message to the response
// with a 500 internal server error.
func InternalErrorf(w http.ResponseWriter, format string, a ...interface{}) {
ErrorCode(w, fmt.Errorf(format, a...), 500)
}
// NotFound writes the json-encoded error message to the response
// with a 404 not found status code.
func NotFound(w http.ResponseWriter, err error) {
ErrorCode(w, err, 404)
}
// NotFoundf writes the json-encoded error message to the response
// with a 404 not found status code.
func NotFoundf(w http.ResponseWriter, format string, a ...interface{}) {
ErrorCode(w, fmt.Errorf(format, a...), 404)
}
// Unauthorized writes the json-encoded error message to the response
// with a 401 unauthorized status code.
func Unauthorized(w http.ResponseWriter, err error) {
ErrorCode(w, err, 401)
}
// Forbidden writes the json-encoded error message to the response
// with a 403 forbidden status code.
func Forbidden(w http.ResponseWriter, err error) {
ErrorCode(w, err, 403)
}
// BadRequest writes the json-encoded error message to the response
// with a 400 bad request status code.
func BadRequest(w http.ResponseWriter, err error) {
ErrorCode(w, err, 400)
}
// BadRequestf writes the json-encoded error message to the response
// with a 400 bad request status code.
func BadRequestf(w http.ResponseWriter, format string, a ...interface{}) {
ErrorCode(w, fmt.Errorf(format, a...), 400)
}
// JSON writes the json-encoded error message to the response
// with a 400 bad request status code.
func JSON(w http.ResponseWriter, v interface{}, status int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
enc := json.NewEncoder(w)
if indent {
enc.SetIndent("", " ")
}
enc.Encode(v)
}