package getUserid
import (
"crypto/tls"
"encoding/json"
"io/ioutil"
"net/http"
"strings"
"time"
)
type User struct { //我们发送get请求需要传递一个参数mobile,我们封装一个对应的结构体
Mobile string `json:"mobile"`
}
type UserResopnseFail struct { //这个是如果访问失败的话,把失败信息保存在结构体创建的对象中
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
Result struct {
Userid string `json:"userid"`
} `json:"result"`
RequestId string `json:"request_id"`
}
type UserResponseSucc struct {// //这个是如果访问成功的话,把成功信息保存在结构体创建的对象中
Errcode int `json:"errcode"`
Errmsg string `json:"errmsg"`
Result struct {
Userid string `json:"userid"`
} `json:"result"`
RequestId string `json:"request_id"`
}
func GetUserID(number,access_token string) (userid string,err error) {
var client *http.Client //封装客户端
var request *http.Request //封装请求
var resp *http.Response //封装响应
var body []byte
urlForUserID := "https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token=" + access_token//拼接URL
client = &http.Client{Transport: &http.Transport{ //对客户端进行一些配置
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}, Timeout: time.Duration(time.Second * 5)}
u := User{
Mobile: number,
} //声明一个结构体对象,把我们传递的参数放进去
usermarshal, err := json.Marshal(&u) //把结构体序列化成byte[]类型
if err != nil {
return
}
reqBody := strings.NewReader(string(usermarshal))//此处再处理一步,才能放入下方请求中
request, err = http.NewRequest(http.MethodPost, urlForUserID, reqBody)
if err != nil {
return
}
resp, err = client.Do(request)//发送请求
if err != nil {
return
}
defer resp.Body.Close()
body, err = ioutil.ReadAll(resp.Body) //把请求到的body转化成byte[]
if err != nil {
return
}
dataSucc := UserResponseSucc{} //声明一个响应对象
err = json.Unmarshal(body, &dataSucc)//把resq.Body反序列化成一个结构体对象
if err != nil {
dateFail := UserResopnseFail{}
err = json.Unmarshal(body, &dateFail)
if err != nil {
return
}
}
return dataSucc.Result.Userid,err
return
}
|