12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- package pkg
- import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "log"
- "net"
- "net/http"
- )
- // 获取外网ip地址
- func GetLocation(ip, key string) string {
- if ip == "127.0.0.1" || ip == "localhost" {
- return "内部IP"
- }
- // 若用户不填写IP,则取客户HTTP之中的请求来进行定位
- url := "https://restapi.amap.com/v3/ip?key=" + key
- log.Println("restapi.amap.com url", url)
- resp, err := http.Get(url)
- if err != nil {
- log.Println("restapi.amap.com failed:", err)
- return "未知位置"
- }
- defer resp.Body.Close()
- s, err := ioutil.ReadAll(resp.Body)
- fmt.Println(string(s))
- m := make(map[string]string)
- err = json.Unmarshal(s, &m)
- if err != nil {
- log.Println("Umarshal failed:", err)
- }
- return m["country"] + "-" + m["province"] + "-" + m["city"] + "-" + m["district"] + "-" + m["isp"]
- }
- // 获取局域网ip地址
- func GetLocalHost() string {
- netInterfaces, err := net.Interfaces()
- if err != nil {
- log.Println("net.Interfaces failed, err:", err.Error())
- }
- for i := 0; i < len(netInterfaces); i++ {
- if (netInterfaces[i].Flags & net.FlagUp) != 0 {
- addrs, _ := netInterfaces[i].Addrs()
- for _, address := range addrs {
- if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
- if ipnet.IP.To4() != nil {
- return ipnet.IP.String()
- }
- }
- }
- }
- }
- return ""
- }
|