先创建一个解析请求的服务
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.POST("/post", PostFunc)
router.GET("/get", GetFunc)
router.Run(":5000")
}
func GetFunc(c *gin.Context) {
name := c.Query("name")
age := c.Query("age")
uri:=c.Request.URL.RawQuery
fmt.Println(name)
fmt.Println(age)
fmt.Println(uri)
}
func PostFunc(c *gin.Context) {
buf := make([]byte, 1024)
n, _ := c.Request.Body.Read(buf)
fmt.Println(string(buf[0:n]))
}
下面是提交请求的功能
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"unsafe"
)
func main() {
fmt.Println(getReq("zhangsan", "18"))
postReq("lisi", 19)
postReqJson1()
var j JsonPost
(*JsonPost).postReqJson2(&j)
}
func getReq(name string, age string) string {
client := &http.Client{}
req, err := http.NewRequest("GET", "http://localhost:5000/get",
nil)
if err != nil {
panic(err)
}
query := req.URL.Query()
query.Add("name", name)
query.Add("age", age)
req.URL.RawQuery = query.Encode()
resp, err := client.Do(req)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
resdata := string(body)
return resdata
}
func postReq(name string, age int) {
client := &http.Client{}
req, err := http.NewRequest("POST", "http://localhost:5000/post",
strings.NewReader(fmt.Sprintf("name=%s&age=%d", name, age)))
if err != nil {
panic(err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := client.Do(req)
defer resp.Body.Close()
}
func postReqJson1() {
url := "http://localhost:5000/post"
name := "wangwu"
age := 20
post := fmt.Sprintf("{\"name\":%s,\"age\":%d}", name, age)
fmt.Println(url, "post", post)
var jsonStr = []byte(post)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("status", resp.Status)
fmt.Println("response:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
type JsonPost struct {
}
func (jp *JsonPost) postReqJson2() {
post := make(map[string]interface{})
post["name"] = "王柳"
post["age"] = 21
bytesData, err := json.Marshal(post)
if err != nil {
fmt.Println(err.Error())
return
}
reader := bytes.NewReader(bytesData)
url := "http://localhost:5000/post"
request, err := http.NewRequest("POST", url, reader)
if err != nil {
fmt.Println(err.Error())
return
}
request.Header.Set("Content-Type", "application/json;charset=UTF-8")
client := http.Client{}
resp, err := client.Do(request)
if err != nil {
fmt.Println(err.Error())
return
}
respBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println(err.Error())
return
}
str := (*string)(unsafe.Pointer(&respBytes))
fmt.Println(*str)
}
|