Files
qv/cmd/web/helpers.go

92 lines
2.3 KiB
Go
Raw Normal View History

2024-12-27 18:03:46 +01:00
package main
import (
api "code.dlmw.ch/dlmw/qv/internal"
"code.dlmw.ch/dlmw/qv/internal/validator"
"encoding/json"
2024-12-28 17:58:01 +01:00
"io"
"net"
"net/http"
"strings"
)
2024-12-27 18:03:46 +01:00
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
app.logger.Error(err.Error())
2025-01-17 19:34:49 +01:00
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
var response = api.ErrorResponse{
Code: http.StatusInternalServerError,
Details: nil,
Message: "There was an error in the request",
}
json.NewEncoder(w).Encode(response)
}
2025-01-13 11:26:18 +01:00
func (app *application) badRequestError(w http.ResponseWriter, r *http.Request, err error) {
2025-01-17 19:34:49 +01:00
w.Header().Set("Content-Type", "application/json")
2025-01-13 11:26:18 +01:00
w.WriteHeader(http.StatusBadRequest)
var response = api.ErrorResponse{
Code: http.StatusBadRequest,
Message: err.Error(),
}
json.NewEncoder(w).Encode(response)
}
func (app *application) clientError(w http.ResponseWriter, status int, message string) {
2025-01-17 19:34:49 +01:00
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
var response = api.ErrorResponse{
Code: status,
Details: nil,
Message: message,
}
json.NewEncoder(w).Encode(response)
}
func (app *application) unprocessableEntityError(w http.ResponseWriter, v validator.Validator) {
2025-01-17 19:34:49 +01:00
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnprocessableEntity)
var response = api.ErrorResponse{
Code: http.StatusUnprocessableEntity,
Details: &map[string]interface{}{
"fields": v.FieldErrors,
},
Message: "Request data is invalid",
}
json.NewEncoder(w).Encode(response)
}
2024-12-28 17:58:01 +01:00
func (app *application) unmarshalRequest(r *http.Request, dst any) error {
body, err := io.ReadAll(r.Body)
if err != nil {
return err
}
2024-12-28 17:58:01 +01:00
err = json.Unmarshal(body, &dst)
if err != nil {
return err
}
return nil
2024-12-27 18:03:46 +01:00
}
func realIP(r *http.Request) string {
var ip string
if tcip := r.Header.Get(http.CanonicalHeaderKey("True-Client-IP")); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get(http.CanonicalHeaderKey("X-Real-IP")); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(http.CanonicalHeaderKey("X-Forwarded-For")); xff != "" {
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
}
if ip == "" || net.ParseIP(ip) == nil {
return ""
}
return ip
}