21700: Install Bundler system-wide in Rails postinst
[arvados.git] / sdk / go / httpserver / error.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: Apache-2.0
4
5 package httpserver
6
7 import (
8         "encoding/json"
9         "fmt"
10         "net/http"
11 )
12
13 type HTTPStatusError interface {
14         error
15         HTTPStatus() int
16 }
17
18 func Errorf(status int, tmpl string, args ...interface{}) error {
19         return errorWithStatus{fmt.Errorf(tmpl, args...), status}
20 }
21
22 func ErrorWithStatus(err error, status int) error {
23         return errorWithStatus{err, status}
24 }
25
26 type errorWithStatus struct {
27         error
28         Status int
29 }
30
31 func (ews errorWithStatus) HTTPStatus() int {
32         return ews.Status
33 }
34
35 type ErrorResponse struct {
36         Errors []string `json:"errors"`
37 }
38
39 func Error(w http.ResponseWriter, error string, code int) {
40         Errors(w, []string{error}, code)
41 }
42
43 func Errors(w http.ResponseWriter, errors []string, code int) {
44         w.Header().Set("Content-Type", "application/json")
45         w.Header().Set("X-Content-Type-Options", "nosniff")
46         w.WriteHeader(code)
47         json.NewEncoder(w).Encode(ErrorResponse{Errors: errors})
48 }