Thanks to visit codestin.com
Credit goes to github.com

Skip to content

chore: idea: unify http responses further #941

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 13 commits into from
Apr 12, 2022
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
use render
  • Loading branch information
f0ssel committed Apr 11, 2022
commit 13cef060630bfa7703a11e1e0cbb33c43f63d207
27 changes: 7 additions & 20 deletions coderd/httpapi/httpapi.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package httpapi

import (
"bytes"
"encoding/json"
"errors"
"fmt"
Expand All @@ -10,6 +9,7 @@ import (
"regexp"
"strings"

"github.com/go-chi/render"
"github.com/go-playground/validator/v10"
)

Expand Down Expand Up @@ -63,30 +63,17 @@ type Error struct {
}

// Write outputs a standardized format to an HTTP response body.
func Write(rw http.ResponseWriter, status int, response interface{}) {
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(true)
err := enc.Encode(response)
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
rw.WriteHeader(status)
_, err = rw.Write(buf.Bytes())
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
func Write(rw http.ResponseWriter, r *http.Request, status int, response interface{}) {
render.Status(r, status)
render.JSON(rw, r, response)
}

// Read decodes JSON from the HTTP request into the value provided.
// It uses go-validator to validate the incoming request body.
func Read(rw http.ResponseWriter, r *http.Request, value interface{}) bool {
err := json.NewDecoder(r.Body).Decode(value)
if err != nil {
Write(rw, http.StatusBadRequest, Response{
Write(rw, r, http.StatusBadRequest, Response{
Message: fmt.Sprintf("read body: %s", err.Error()),
})
return false
Expand All @@ -101,14 +88,14 @@ func Read(rw http.ResponseWriter, r *http.Request, value interface{}) bool {
Code: validationError.Tag(),
})
}
Write(rw, http.StatusBadRequest, Response{
Write(rw, r, http.StatusBadRequest, Response{
Message: "Validation failed",
Errors: apiErrors,
})
return false
}
if err != nil {
Write(rw, http.StatusInternalServerError, Response{
Write(rw, r, http.StatusInternalServerError, Response{
Message: fmt.Sprintf("validation: %s", err.Error()),
})
return false
Expand Down