sslobodr | d046be8 | 2019-01-16 10:02:22 -0500 | [diff] [blame] | 1 | // Copyright 2015 The etcd Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package httptypes |
| 16 | |
| 17 | import ( |
| 18 | "encoding/json" |
| 19 | "net/http" |
| 20 | |
| 21 | "github.com/coreos/pkg/capnslog" |
| 22 | ) |
| 23 | |
| 24 | var ( |
| 25 | plog = capnslog.NewPackageLogger("github.com/coreos/etcd", "etcdserver/api/v2http/httptypes") |
| 26 | ) |
| 27 | |
| 28 | type HTTPError struct { |
| 29 | Message string `json:"message"` |
| 30 | // Code is the HTTP status code |
| 31 | Code int `json:"-"` |
| 32 | } |
| 33 | |
| 34 | func (e HTTPError) Error() string { |
| 35 | return e.Message |
| 36 | } |
| 37 | |
| 38 | func (e HTTPError) WriteTo(w http.ResponseWriter) error { |
| 39 | w.Header().Set("Content-Type", "application/json") |
| 40 | w.WriteHeader(e.Code) |
| 41 | b, err := json.Marshal(e) |
| 42 | if err != nil { |
| 43 | plog.Panicf("marshal HTTPError should never fail (%v)", err) |
| 44 | } |
| 45 | if _, err := w.Write(b); err != nil { |
| 46 | return err |
| 47 | } |
| 48 | return nil |
| 49 | } |
| 50 | |
| 51 | func NewHTTPError(code int, m string) *HTTPError { |
| 52 | return &HTTPError{ |
| 53 | Message: m, |
| 54 | Code: code, |
| 55 | } |
| 56 | } |