先创建一个解析请求的服务
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 (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
fmt.Println(getReq("zhangsan", "18"))
postReq("lisi", 19)
}
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()
}