話很少說直接上代碼web
package main //導入須要的包 import ( "errors" "fmt" "io/ioutil" "net" "net/http" "os" "strings" ) //獲取本地機器ip列表 func externalIP() (net.IP, error) { ifaces, err := net.Interfaces() if err != nil { return nil, err } for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { return nil, err } for _, addr := range addrs { ip := getIpFromAddr(addr) if ip == nil { continue } return ip, nil } } return nil, errors.New("connected to the network?") } //從本地機器ip列表中找到真實ip func getIpFromAddr(addr net.Addr) net.IP { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { return nil } ip = ip.To4() if ip == nil { return nil // not an ipv4 address } return ip } //獲取本機名稱 func getHostname() string{ name, err := os.Hostname() if err != nil { panic(err) } return name //fmt.Println("hostname:", name) } //發送一個post請求,傳遞含有變量的json數據 func httpPostJson(getip string , gethostname string) { url := "https://is-cmdb-test.test.gifshow.com/cmdb-web/api/v1/machine/add" method := "POST" payload := strings.NewReader("{\"hostName\": \""+gethostname+"\",\"ip\": \""+getip+"\",\"env\":\"開發環境\",\"machineRoom\":\"DZ\",\"info\":\"\",\"label\":\"k8s\",\"user\":\"劉緒衝\"}") client := &http.Client { } req, err := http.NewRequest(method, url, payload) if err != nil { fmt.Println(err) } req.Header.Add("Content-Type", "application/json") //req.Header.Add("Cookie", "accessproxy_session=22fba8b9-dd1b-4495-bf79-020db9b1e11b; apdid=3c9fb385-1111-494a-9251-cf84935ce3c58e620eacfc6f038594c6112f2642d89a:1610612991:1") res, err := client.Do(req) defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) fmt.Println(string(body)) } func main() { ip, err := externalIP() if err != nil { fmt.Println(err) } fmt.Println("本機ip:",ip.String()) //把ip和hostnmae賦值給新的變量 getip := ip.String() gethostname := getHostname() httpPostJson(getip , gethostname) }