Created
October 2, 2023 11:16
-
-
Save Hunrik/02a137e8ffa904a7e6fcf697364db3e0 to your computer and use it in GitHub Desktop.
HTTP Server Response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httpserver | |
import ( | |
"encoding/json" | |
"net/http" | |
) | |
func CreateTodo(w http.ResponseWriter, r *http.Request) { | |
ctx := r.Context() | |
if !can.I(ctx, "create-todo") { | |
ErrUnauthorized().Render(w, r) | |
return | |
} | |
var reqBody todo.Todo | |
if err := json.NewDecoder(r.Body).Decode(&reqBody); err != nil { | |
ErrBadRequest(err).Render(w, r) | |
return | |
} | |
createdTodo, err := todo.Create(ctx, reqBody) | |
if err != nil { | |
ErrInternalServerError(err).Render(w, r) | |
return | |
} | |
TodoCreatedResponse(createdTodo).Render(w, r) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package httpserver | |
import ( | |
"encoding/json" | |
"net/http" | |
) | |
type ErrResponse struct { | |
Err error `json:"-"` | |
HTTPStatusCode int `json:"-"` | |
StatusText string `json:"status"` | |
ErrorText string `json:"error,omitempty"` | |
} | |
func (e *ErrResponse) Render(w http.ResponseWriter, r *http.Request) error { | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(e.HTTPStatusCode) | |
return json.NewEncoder(w).Encode(e) | |
} | |
func ErrBadRequest(err error) *ErrResponse { | |
return &ErrResponse{ | |
Err: err, | |
HTTPStatusCode: http.StatusBadRequest, | |
StatusText: "Bad Request", | |
ErrorText: err.Error(), | |
} | |
} | |
func ErrUnauthorized() *ErrResponse { | |
return &ErrResponse{ | |
HTTPStatusCode: http.StatusUnauthorized, | |
StatusText: "Unauthorized", | |
ErrorText: "You are not authorized to perform this action.", | |
} | |
} | |
func ErrInternalServerError(err error) *ErrResponse { | |
return &ErrResponse{ | |
Err: err, | |
HTTPStatusCode: http.StatusInternalServerError, | |
StatusText: "Internal Server Error", | |
ErrorText: err.Error(), | |
} | |
} | |
type TodoResponse struct { | |
HTTPStatusCode int `json:"-"` | |
todo.Todo | |
} | |
func (e *TodoResponse) Render(w http.ResponseWriter, r *http.Request) error { | |
w.Header().Set("Content-Type", "application/json") | |
if e.HTTPStatusCode == 0 { | |
e.HTTPStatusCode = http.StatusOK | |
} | |
w.WriteHeader(e.HTTPStatusCode) | |
return json.NewEncoder(w).Encode(e) | |
} | |
func TodoCreatedResponse(t todo.Todo) *TodoResponse { | |
return &TodoResponse{ | |
HTTPStatusCode: http.StatusCreated, | |
Todo: t, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment