123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121 |
- package http
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
- "unsafe"
- )
- func GetReq(url string) *http.Response {
- client := &http.Client{}
- req, err := http.NewRequest("GET", url, nil)
- if err != nil {
- //panic(err)
- fmt.Println(err.Error())
- }
- resp, err := client.Do(req)
- if err != nil {
- //panic(err)
- fmt.Println(err.Error())
- }
- //defer func(Body io.ReadCloser) {
- // err := Body.Close()
- // if err != nil {
- // fmt.Print("Body close err" + err.Error())
- // }
- //}(resp.Body)
- return resp
- }
- //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()
- //
- //}
- // PostReqJson 通过json提交post
- func PostReqJson(url string, json []byte) *http.Response {
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(json))
- req.Header.Set("Content-Type", "application/json")
- client := &http.Client{}
- resp, err := client.Do(req)
- if err != nil {
- panic(err)
- }
- defer func(Body io.ReadCloser) {
- err := Body.Close()
- if err != nil {
- fmt.Print("Body close err" + err.Error())
- }
- }(resp.Body)
- return resp
- }
- 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
- }
- //byte数组直接转成string,优化内存
- str := (*string)(unsafe.Pointer(&respBytes))
- fmt.Println(*str)
- }
- // DeleteReq 发送delete请求
- func DeleteReq(url string) *http.Response {
- client := &http.Client{}
- req, err := http.NewRequest("DELETE", url, nil)
- if err != nil {
- panic(err)
- }
- resp, err := client.Do(req)
- if err != nil {
- panic(err)
- }
- return resp
- }
|