feat(api): replace all calls to http.Error with custom Error writer

pull/417/head
Anthony Lapenna 2017-01-24 16:35:48 +13:00
parent 1a868be6ea
commit d03e992b4f
4 changed files with 10 additions and 11 deletions

View File

@ -135,7 +135,7 @@ type unixSocketHandler struct {
func (h *unixSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
conn, err := net.Dial("unix", h.path)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Error(w, err, http.StatusInternalServerError, nil)
return
}
c := httputil.NewClientConn(conn, nil)
@ -143,7 +143,7 @@ func (h *unixSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
res, err := c.Do(r)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Error(w, err, http.StatusInternalServerError, nil)
return
}
defer res.Body.Close()
@ -154,6 +154,6 @@ func (h *unixSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}
if _, err := io.Copy(w, res.Body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Error(w, err, http.StatusInternalServerError, nil)
}
}

View File

@ -55,7 +55,9 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Error writes an API error message to the response and logger.
func Error(w http.ResponseWriter, err error, code int, logger *log.Logger) {
// Log error.
logger.Printf("http error: %s (code=%d)", err, code)
if logger != nil {
logger.Printf("http error: %s (code=%d)", err, code)
}
// Write generic error response.
w.WriteHeader(code)

View File

@ -47,13 +47,13 @@ func (service *middleWareService) middleWareAuthenticate(next http.Handler) http
}
if token == "" {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
Error(w, portainer.ErrUnauthorized, http.StatusUnauthorized, nil)
return
}
err := service.jwtService.VerifyToken(token)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
Error(w, err, http.StatusUnauthorized, nil)
return
}

View File

@ -1,7 +1,6 @@
package http
import (
"fmt"
"io/ioutil"
"log"
"net/http"
@ -40,15 +39,13 @@ func (handler *TemplatesHandler) handleGetTemplates(w http.ResponseWriter, r *ht
resp, err := http.Get(handler.templatesURL)
if err != nil {
log.Print(err)
http.Error(w, fmt.Sprintf("Error making request to %s: %s", handler.templatesURL, err.Error()), http.StatusInternalServerError)
Error(w, err, http.StatusInternalServerError, handler.Logger)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Print(err)
http.Error(w, "Error reading body from templates URL", http.StatusInternalServerError)
Error(w, err, http.StatusInternalServerError, handler.Logger)
return
}
w.Header().Set("Content-Type", "application/json")