client
比较简单的方式有两个:(下面的代码是抄的)
1.http.post() / http.get()
func httpPost() {
resp, err := http.Post("http://www.01happy.com/demo/accept.php",
"application/x-www-form-urlencoded",
strings.NewReader("name=cjb"))
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
func httpDo() {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://www.01happy.com/demo/accept.php", strings.NewReader("name=cjb")) //bytes.NewReader()
if err != nil {
// handle error
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Cookie", "name=anny")
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
// handle error
}
fmt.Println(string(body))
}
- query 1
q := url.Values{}
q.Set("username", "user")
q.Set("password", "passwd")
data := q.Encode()
url := "http://localhost"
reqest, err := http.NewRequest("POST", url, strings.NewReader(data))
u, _ := url.Parse("http://localhost")
q := u.Query()
// q := url.Values{} //also work
q.Set("username", "user")
q.Set("password", "passwd")
u.RawQuery = q.Encode()
res, err := http.Get(u.String());
q :=request.URL.Query()
//q := url.Values{} //also work
q.Set("username", "user")
q.Set("password", "passwd")
request.URL.RawQuery=q.Encode()
response, _ := client.Do(request)
- header
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Content-Type", "application/json; charset=utf-8")
- 不确定返回body的数据时如何解析2
result, _:= ioutil.ReadAll(r.Body)
r.Body.Close()
fmt.Printf("%s\n", result)
//未知类型的推荐处理方法
var f interface{}
json.Unmarshal(result, &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case float64:
fmt.Println(k,"is float64",vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
}
}
server
//url 中的参数
r.ParseForm()
r.FormValue("key")
//from data 参数
r.ParseMultipartForm(1<<10)
r.Form.Get("key")
// 或者下面这样:
mReader := multipart.NewReader(r.Body, boundary)
for {
var part *multipart.Part
part, err = mReader.NextPart()
if err == io.EOF{
break;
}
参考:
这两篇都不太好,不过例子可以跑通。
https://www.cnblogs.com/mafeng/p/7068837.html
https://studygolang.com/articles/4830