All checks were successful
Build and Push Docker Image on Tag / Build and Push Docker Image (push) Successful in 15m31s
Code was copied from https://github.com/go-chi/chi/blob/master/middleware/realip.go
92 lines
2.3 KiB
Go
92 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
api "code.dlmw.ch/dlmw/qv/internal"
|
|
"code.dlmw.ch/dlmw/qv/internal/validator"
|
|
"encoding/json"
|
|
"io"
|
|
"net"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func (app *application) serverError(w http.ResponseWriter, r *http.Request, err error) {
|
|
app.logger.Error(err.Error())
|
|
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)
|
|
}
|
|
|
|
func (app *application) badRequestError(w http.ResponseWriter, r *http.Request, err error) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
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) {
|
|
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) {
|
|
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)
|
|
}
|
|
|
|
func (app *application) unmarshalRequest(r *http.Request, dst any) error {
|
|
body, err := io.ReadAll(r.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
err = json.Unmarshal(body, &dst)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
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
|
|
}
|