您的位置:首页 > 产品设计 > UI/UE

golang 发送post请求 其body中json对象使用变量作为value

2021-01-14 17:44 1196 查看

话不多说直接上代码

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://myurl"
method := "POST"

payload := strings.NewReader("{\"hostName\": \""+gethostname+"\",\"ip\": \""+getip+"\"}")

client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")

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)

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐