15370: Fix flaky test.
[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 func Errorf(status int, tmpl string, args ...interface{}) error {
14         return errorWithStatus{fmt.Errorf(tmpl, args...), status}
15 }
16
17 func ErrorWithStatus(err error, status int) error {
18         return errorWithStatus{err, status}
19 }
20
21 type errorWithStatus struct {
22         error
23         Status int
24 }
25
26 func (ews errorWithStatus) HTTPStatus() int {
27         return ews.Status
28 }
29
30 type ErrorResponse struct {
31         Errors []string `json:"errors"`
32 }
33
34 func Error(w http.ResponseWriter, error string, code int) {
35         Errors(w, []string{error}, code)
36 }
37
38 func Errors(w http.ResponseWriter, errors []string, code int) {
39         w.Header().Set("Content-Type", "application/json")
40         w.Header().Set("X-Content-Type-Options", "nosniff")
41         w.WriteHeader(code)
42         json.NewEncoder(w).Encode(ErrorResponse{Errors: errors})
43 }