68 lines
1.4 KiB
Go
68 lines
1.4 KiB
Go
|
package utils
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"github.com/ipipdotnet/ipdb-go"
|
||
|
"net"
|
||
|
"net/http"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
const (
|
||
|
remoteAddrHeader = "X-NAV-REMOTE-IP"
|
||
|
)
|
||
|
|
||
|
type errorMessage struct {
|
||
|
Error string `json:"error"`
|
||
|
}
|
||
|
|
||
|
func ResponseWithError(resp http.ResponseWriter, statusCode int, message string) {
|
||
|
resp.Header().Set("Content-Type", "text/plain")
|
||
|
resp.WriteHeader(statusCode)
|
||
|
resp.Write([]byte("error: " + message))
|
||
|
}
|
||
|
|
||
|
func ResponseWithJsonError(resp http.ResponseWriter, statusCode int, message string) {
|
||
|
resp.Header().Set("Content-Type", "application/json")
|
||
|
resp.WriteHeader(statusCode)
|
||
|
encoder := json.NewEncoder(resp)
|
||
|
err := encoder.Encode(&errorMessage{
|
||
|
Error: message,
|
||
|
})
|
||
|
if err != nil {
|
||
|
// This should never happen
|
||
|
panic("json marshal failed, check code")
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func GetRemoteIP(req *http.Request) string {
|
||
|
if addr := req.Header.Get(remoteAddrHeader); addr != "" {
|
||
|
if net.ParseIP(addr).To4() == nil {
|
||
|
return ""
|
||
|
}
|
||
|
return addr
|
||
|
}
|
||
|
host, _, err := net.SplitHostPort(req.RemoteAddr)
|
||
|
if err != nil {
|
||
|
return ""
|
||
|
}
|
||
|
if net.ParseIP(host).To4() == nil {
|
||
|
return ""
|
||
|
}
|
||
|
return host
|
||
|
}
|
||
|
|
||
|
func BuildLocation(info *ipdb.CityInfo) string {
|
||
|
ret := ""
|
||
|
if info.CountryName != "" {
|
||
|
ret += info.CountryName + " "
|
||
|
}
|
||
|
if info.RegionName != "" {
|
||
|
ret += info.RegionName + " "
|
||
|
}
|
||
|
if info.CityName != "" {
|
||
|
ret += info.CityName + " "
|
||
|
}
|
||
|
return strings.TrimSpace(ret)
|
||
|
}
|