Code refactor, adding GoLand workspace with Bazel plugin.
This commit is contained in:
9
utils/BUILD.bazel
Normal file
9
utils/BUILD.bazel
Normal file
@ -0,0 +1,9 @@
|
||||
load("@io_bazel_rules_go//go:def.bzl", "go_library")
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = ["utils.go"],
|
||||
importpath = "git.eve.moe/jackyyf/navigator/utils",
|
||||
visibility = ["//visibility:public"],
|
||||
deps = ["@com_github_ipipdotnet_ipdb_go//:go_default_library"],
|
||||
)
|
67
utils/utils.go
Normal file
67
utils/utils.go
Normal file
@ -0,0 +1,67 @@
|
||||
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)
|
||||
}
|
Reference in New Issue
Block a user