1、概述
最近接触了开发语言go,在研发过程中需要用到网络请求,以此记录一下请求过程中的问题和实现
2、go实现GET请求
get请求一般比较简单,不需要传参数直接请求即可,只是需要解析返回的参数而已。下面是实例代码:
备注:默认返回的数据是json格式,如下图所示的实例结构体
import (
"fmt"
"net/http"
"encoding/json"
"io/ioutil"
)
`
get请求返回数据假如如下所示
{
"code": 200,
"msg": "成功",
"data": [
{
"user": "jelly1",
"name": "工厂1",
"list": []
},
{
"user": "jelly2",
"name": "工厂2",
"list": ["apple","banana"]
}
}
`
type newResource struct{
User string `json:"user"`
Name string `json:"name"`
List []string `json:"list"`
}
func GetAll() error{
req, err := http.NewRequest("GET", "http://ip:port/url", nil)
if err != nil {
fmt.Println("err:",err)
return err,nil
}
req.Header.Set("Content-Type", "application/json")
res,err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("err:",err)
return err,nil
}
defer res.Body.Close()
//得到返回结果
body, _ := ioutil.ReadAll(res.Body)
bodystr := string(body)
//对返回的json数据做解析
var datajson map[string]interface{}
err = json.Unmarshal([]byte(bodystr), &datajson)
//fmt.Println(datajson["data"])
jsonbyte, err := json.Marshal(datajson["data"])
var datasss []newResource
err = json.Unmarshal(jsonbyte, &datasss)
if err != nil {
fmt.Println("err:",err)
return err,nil
}
return err,datasss
}
此处我想表达的意思是解析的时候数据需要来两遍,后面才能使用否则interface{}到时候格式调用会报错:
jsonbyte, err := json.Marshal(datajson["data"])
var datasss []newResource
err = json.Unmarshal(jsonbyte, &datasss)
上面这三行代码是将
var datajson map[string]interface{}的字符类型的interface完全转换成json,好给接下来使用数据更方便。json的Unmarshal和Marshal转换都使用了两次
3、go实现POST请求
POST请求这个地方主要涉及到几个问题,传json数据,传xml数据和传结构体数据
传输xml数据:
//newdata为xml的字符串数据
client := &http.Client{}
req, err := http.NewRequest("POST","http://ip:port/url" , strings.NewReader(newdata))
if err != nil {
fmt.Println("err:",err)
return err
}
req.Header.Set("Content-Type", "application/xml")
resp, err := client.Do(req)
if err != nil {
fmt.Println("err:",err)
return err
}
defer resp.Body.Close()
传json数据和结构体数据
client := &http.Client{}
//client := &http.Client{}
bs, _ := json.Marshal(senddata) //senddata为结构体数据或者json数据
var out bytes.Buffer
json.Indent(&out, bs, "", "\t")
//common.PrintDebug(out.String())
req, err := http.NewRequest("POST", "http://ip:port/url", strings.NewReader(out.String()))
if err != nil {
//common.PrintDebug("err:",err)
return
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
//common.PrintDebug("err:",err)
return
}
//common.PrintDebug("resp.StatusCode:",resp.StatusCode)
defer resp.Body.Close()
4、go网络请求加https
如果在需要https的网络请求,代码如下
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
client用图中的加了tls的client进行连接,url使用https即可
InsecureSkipVerify: true
上面这句的意思忽略证书验证,如果你的服务器是自己生成的证书,不是CA机构颁发的证书,需要设置这个,否则无法正常连接,如果是CA颁发的证书,true改成false即可,好像也可以不用设置,默认是false