package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
// 处理POST请求
func dealPostRequestHandler(w http.ResponseWriter, r *http.Request) {
// 请求的主机
fmt.Println(r.Host)
// 请求头信息
//fmt.Println("header content info : ", r.Header)
// 请求体数据
bodyContent, err := ioutil.ReadAll(r.Body)
if err != nil && err != io.EOF {
fmt.Printf("read body content failed, err:[%s]\n", err.Error())
return
}
fmt.Printf("body content:[%s]\n", string(bodyContent))
//返回响应内容
json.NewEncoder(w).Encode(string(bodyContent))
}
// 处理GET请求
func dealGetRequestHandler(w http.ResponseWriter, r *http.Request) {
// 请求的主机
fmt.Println(r.Host)
// 获取请求的参数
query := r.URL.Query()
jsonStr, err := json.Marshal(query)
if err != nil {
return
}
fmt.Println("get request param: " + string(jsonStr) + "\n")
// 解析请求参数
name, ok := query["name"]
if !ok || len(name[0]) < 1 {
return
}
fmt.Println("get param-name: " + name[0])
json.NewEncoder(w).Encode(name[0])
}
func main() {
http.HandleFunc("/req/post", dealPostRequestHandler)
http.HandleFunc("/req/get", dealGetRequestHandler)
http.ListenAndServe(":8005", nil)
}
该server监听8005端口,实现了处理POST和GET请求的handler。
2、创建测试net/http的文件(文件名:TestNetHttp.go), 代码如下:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
// 使用http.Post , 参数格式:json
func httpPost(requestUrl string, params map[string]string) (err error) {
jsonData, _ := json.Marshal(params)
resp, err := http.Post(requestUrl, "application/x-www-form-urlencoded", bytes.NewReader(jsonData))
if err != nil {
fmt.Println("send post request failed, err: [%s]", err.Error())
return
}
// 客户必须在完成后关闭响应主体
defer resp.Body.Close()
bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
}
// 使用http.Client , 参数格式:json
func httpClient(requestUrl string, params map[string]string) (err error) {
client := http.Client{}
jsonData, _ := json.Marshal(params)
requestPost, err := http.NewRequest("POST", requestUrl, bytes.NewReader(jsonData))
resp, err := client.Do(requestPost)
if err != nil {
fmt.Printf("send post request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close()
bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
}
// 发送 form 表单格式的post请求
func httpPostForm(requestUrl string) (err error) {
data := url.Values{}
data.Add("name", "admin")
data.Add("passwd", "123456")
resp, err := http.PostForm(requestUrl, data)
if err != nil {
fmt.Println("send post request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close()
bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
}
// 发送基本的GET请求
func httpGet(url string) (err error) {
resp, err := http.Get(url)
if err != nil {
fmt.Printf("send get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close()
bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
}
// 发送GET请求, 把参数做成变量放到url中。
func httpGetOne(requestUrl string) (err error) {
Url, err := url.Parse(requestUrl)
if err != nil {
fmt.Printf("requestUrl parse failed, err:[%s]", err.Error())
return
}
params := url.Values{}
params.Set("query", "googlesearch")
params.Set("content", "golang")
Url.RawQuery = params.Encode()
requestUrl = Url.String()
fmt.Printf("requestUrl:[%s]\n", requestUrl)
resp, err := http.Get(requestUrl)
if err != nil {
fmt.Printf("get request failed, err:[%s]", err.Error())
return
}
defer resp.Body.Close()
bodyContent, err := ioutil.ReadAll(resp.Body)
fmt.Printf("resp status code:[%d]\n", resp.StatusCode)
fmt.Printf("resp body data:[%s]\n", string(bodyContent))
return
}
func main() {
// mock post请求
//post_request_url := "http://localhost:8005/req/post"
// 发送json格式的post请求
//params := map[string]string{"name":"admin","passwd":"123456"}
//httpPost(post_request_url, params)
//httpClient(post_request_url, params)
// 发送form格式的post请求
//httpPostForm(post_request_url)
// mock get请求
//httpGet("http://localhost:8005/req/get?name=admin")
httpGetOne("http://localhost:8005/req/get")
}
该文件包含了3个POST请求方法(其中2个发送json格式的数据,1个发送form格式的数据),分别使用了http.POST 、 http.Client 、http.PostForm 。 2个GET请求的方法。
测试方法:
1、运行LocalServer.go
2、运行TestNetHttp.go,分别发送POST和GET请求
示例:发送httPost请求,http server的控制台打印结果:
localhost:8005
body content:[{"name":"admin","passwd":"123456"}]
发送http请求的测试端打印结果:
resp status code:[200]
resp body data:["{\"name\":\"admin\",\"passwd\":\"123456\"}"
]
参考:
https://www.cnblogs.com/kaichenkai/p/11365020.html
https://cloud.tencent.com/developer/section/1143633
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)