FloorVisualizer/internal/handler/router.go

43 lines
986 B
Go
Raw Normal View History

package handler
import (
"encoding/json"
"net/http"
"net/url"
"floorvisualizer/internal/model"
)
func NewProxyClient(proxyURLStr string) *http.Client {
u, _ := url.Parse(proxyURLStr)
if u == nil {
return http.DefaultClient
}
return &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(u)}}
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if status >= 400 {
msg := "Unknown error"
switch x := v.(type) {
case string:
msg = x
case map[string]string:
if e, ok := x["error"]; ok {
msg = e
}
}
json.NewEncoder(w).Encode(model.ApiError{Code: status, Error: msg})
return
}
json.NewEncoder(w).Encode(model.ApiResponse{Code: status, Data: v})
}
func writeErr(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(model.ApiError{Code: status, Error: msg})
}