everybody loves a refactor
This commit is contained in:
36
internal/respond/error.go
Normal file
36
internal/respond/error.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Package respond provides utilities for raw HTTP responses that don't fit into the throw or notify categories
|
||||
package respond
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func OK(w http.ResponseWriter) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func BadRequest(w http.ResponseWriter, err error) {
|
||||
respondError(w, http.StatusBadRequest, err)
|
||||
}
|
||||
|
||||
func NotFound(w http.ResponseWriter, err error) {
|
||||
respondError(w, http.StatusNotFound, err)
|
||||
}
|
||||
|
||||
func Conflict(w http.ResponseWriter, err error) {
|
||||
respondError(w, http.StatusConflict, err)
|
||||
}
|
||||
|
||||
func respondError(w http.ResponseWriter, statusCode int, err error) {
|
||||
details := map[string]any{
|
||||
"error": statusCode,
|
||||
"details": fmt.Sprintf("%s", err),
|
||||
}
|
||||
resp, err := json.Marshal(details)
|
||||
w.WriteHeader(statusCode)
|
||||
if err == nil {
|
||||
_, _ = w.Write(resp)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user