39 lines
842 B
Go
39 lines
842 B
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"strconv"
|
|
)
|
|
|
|
func writeJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(statusCode)
|
|
err := json.NewEncoder(w).Encode(data)
|
|
if err != nil {
|
|
log.Fatalf("Failed to write response. Error: %s\n", err)
|
|
}
|
|
}
|
|
|
|
func writeErrorResponse(w http.ResponseWriter, statusCode int, message string) {
|
|
writeJSONResponse(w, statusCode, map[string]string{
|
|
"error": message,
|
|
})
|
|
}
|
|
|
|
func readJSONRequest(r *http.Request, data interface{}) error {
|
|
err := json.NewDecoder(r.Body).Decode(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func parseIDFromURL(r *http.Request) (int64, error) {
|
|
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
return id, nil
|
|
}
|