github.com/OpsMx/go-app-base@v0.0.24/httputil/errors.go (about) 1 // Copyright 2022 OpsMx, Inc 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 httputil 16 17 import ( 18 "encoding/json" 19 "net/http" 20 21 "log" 22 ) 23 24 // StatusCodeOK returns true if the error code provided is between 25 // 200 and 2999, inclusive. 26 func StatusCodeOK(statusCode int) bool { 27 return statusCode >= 200 && statusCode <= 299 28 } 29 30 // httpError defines a simple struct to return JSON formatted error 31 // messages. 32 type httpError struct { 33 Status string `json:"status,omitempty" yaml:"status,omitempty"` 34 Code int `json:"code,omitempty" yaml:"code,omitempty"` 35 Error interface{} `json:"error,omitempty" yaml:"error,omitempty"` 36 } 37 38 // SetError returns a JSON error message with a Status field set to 'error', 39 // a 'code' set to the provided code, and the 'error' set to the provided 40 // content. 41 // 42 // Prior to calling, nothing should be written to the writer, and afterwards 43 // nothing should be written. 44 // 45 // The content-type will be set to application/json. 46 func SetError(w http.ResponseWriter, statusCode int, message interface{}) { 47 w.Header().Set("content-type", "application/json") 48 w.WriteHeader(statusCode) 49 m := httpError{Status: "error", Code: statusCode, Error: message} 50 d, err := json.Marshal(m) 51 if err != nil { 52 log.Printf("marshalling error json: %v", err) 53 } 54 l, err := w.Write(d) 55 if l != len(d) { 56 log.Printf("writing error json: %d of %d bytes written", l, len(d)) 57 return 58 } 59 if err != nil { 60 log.Printf("writing error json: %v", err) 61 } 62 }