我正在开发将在我们用户的服务器上运行的客户端应用程序。我想猜测一下当前位置,例如America/New_York 或 Europe/London 以中继到该服务,以便它可以根据 UTC 偏移量和夏令时规则计算客户端上的当前时间。
关于应用程序如何最好地猜测当前位置有什么想法吗?我知道我可以获得像“PST”这样的当前时区,但这并没有告诉我我需要知道什么。
最佳答案
在 Ubuntu(可能还有其他 Linux 发行版)上,/etc/timezone
包含位置的描述(例如 Australia/Sydney
),如果在服务器已设置。正如评论中所提到的,不能保证这将是正确的。
如果你可以访问互联网,你可以向 https://freegeoip.net/json/
或类似的东西发出 GET 请求,这将返回一个包含你的 ip 的地理定位数据的 json 对象。同样,有很多因素会影响其准确性。
下面的代码完成了这两件事,请注意,为简洁起见,没有错误检查(这很糟糕)。
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type LocationData struct {
IP string `json:"ip"`
CountryCode string `json:"country_code"`
CountryName string `json:"country_name"`
RegionCode string `json:"region_code"`
RegionName string `json:"region_name"`
City string `json:"city"`
ZipCode string `json:"zip_code"`
TimeZone string `json:"time_zone"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
MetroCode int `json:"metro_code"`
}
func main() {
// Using /etc/timezone
buf, _ := ioutil.ReadFile("/etc/timezone")
fmt.Printf("%s", buf)
// Using freegeoip
var locationData LocationData
resp, _ := http.Get("https://freegeoip.net/json/")
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
decoder.Decode(&locationData)
fmt.Println(locationData.TimeZone)
}
关于go - 确定当前主机位置,例如欧洲/伦敦,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47277005/