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 }