话不多说直接上代码

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)

}