Golang发送GET、POST、PUT、DELETE请求

是个懒人 · · 3453 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

golang发送GET、POST、PUT、DELETE请求

package request

import (
    "compress/gzip"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
    "net/url"
)

type Param map[string]interface{}

type request struct {
    Url         string
    Params      Param
    Method      string
    Status      string
    StatusCode  int
    Header      map[string][]string
    Body        string
    Response    *http.Response
    Proto       string
    Host        string
    URL         *url.URL
}

var req *request

func (r *request) get(url string, params Param) (rest *request, err error) {
    return r.do(url, params, "GET")
}

func (r *request) post(url string, params Param) (rest *request, err error) {
    return r.do(url, params, "POST")
}

func (r *request) put(url string, params Param) (rest *request, err error) {
    return r.do(url, params, "PUT")
}

func (r *request) delete(url string, params Param) (rest *request, err error) {
    return r.do(url, params, "DELETE")
}

func (r *request) do(url string, params Param, method string) (rest *request, err error) {
    reqs, err := http.NewRequest(method, url, nil)
    if err != nil {
        return nil, err
    }
    // 添加header
    reqs.Header.Add("Authorization", "token_value")
    reqs.Header.Add("Content-Type", "text/plain; charset=UTF-8")
    reqs.Header.Add("User-Agent", "Go-http-client/1.14")
    reqs.Header.Add("Transfer-Encoding", "chunked")
    reqs.Header.Add("Accept-Encoding", "gzip, deflate")
    // 设置参数
    q := reqs.URL.Query()
    for k, v := range params {
        q.Add(k, fmt.Sprint(v))
    }
    reqs.URL.RawQuery = q.Encode()
    res, err := http.DefaultClient.Do(reqs)
    if err != nil {
        return nil, err
    }
    defer res.Body.Close()
    var body string
    if res.StatusCode == 200 {
        switch res.Header.Get("Content-Encoding") {
        case "gzip":
            reader, _ := gzip.NewReader(res.Body)
            for {
                buf := make([]byte, 1024)
                n, err := reader.Read(buf)
                if err != nil && err != io.EOF {
                    panic(err)
                }
                if n == 0 {
                    break
                }
                body += string(buf)
            }
        default:
            bodyByte, _ := ioutil.ReadAll(res.Body)
            body = string(bodyByte)
        }
    } else {
        bodyByte, _ := ioutil.ReadAll(res.Body)
        body = string(bodyByte)
    }
    rest = &request{
        Url:        url,
        Params:     params,
        Method:     method,
        Body:       body,
        Header:     reqs.Header,
        Response:   res,
        Proto:      reqs.Proto,
        Host:       reqs.Host,
        URL:        reqs.URL,
        Status:     res.Status,
        StatusCode: res.StatusCode,
    }
    return rest, nil
}

func (r *request) Dump() {
    fmt.Println("----------------------------------------------------")
    fmt.Println(r.Method, r.Proto)
    fmt.Println("Host", ":", r.Host)
    fmt.Println("URL", ":", r.URL)
    fmt.Println("RawQuery", ":", r.URL.RawQuery)
    for key, val := range r.Header {
        fmt.Println(key, ":", val)
    }
    fmt.Println("----------------------------------------------------")
    fmt.Println("Status", ":", r.Status)
    for key, val := range r.Response.Header {
        fmt.Println(key, ":", val)
    }
}

func Get(url string, params Param) (rest *request, err error) {
    return req.get(url, params)
}

func Post(url string, params Param) (rest *request, err error) {
    return req.post(url, params)
}

func Put(url string, params Param) (rest *request, err error) {
    return req.put(url, params)
}

func Delete(url string, params Param) (rest *request, err error) {
    return req.delete(url, params)
}

GET测试请求

func main() {
    url := "http://www.beego.cn/api/demo"
    r, err := request.Get(url, request.Param{"id": 20, "name": "赵云"})
    if err == nil {
        r.Dump()
        fmt.Println("----------------------------------------------------")
        fmt.Println("body:", r.Body)
    }
}

GET HTTP/1.1
Host : www.beego.cn
URL : http://www.beego.cn/api/demo?id=20&name=%E8%B5%B5%E4%BA%91
RawQuery : id=20&name=%E8%B5%B5%E4%BA%91
Authorization : [token_value]
Content-Type : [text/plain; charset=UTF-8]
User-Agent : [Go-http-client/1.14]
Transfer-Encoding : [chunked]
Accept-Encoding : [gzip, deflate]


Status : 200 OK
Date : [Thu, 09 Apr 2020 15:26:56 GMT]
Content-Type : [application/json; charset=utf-8]
Content-Length : [53]
Connection : [keep-alive]
Server : [nginx/1.15.5]


body: {
"method": "GET",
"name": "赵云",
"id": 20
}


POST测试请求

func main() {
    url := "http://www.beego.cn/api/demo"
    r, err = request.Post(url, request.Param{"id": 21, "name": "马超"})
    if err == nil {
        r.Dump()
        fmt.Println("----------------------------------------------------")
        fmt.Println("body:", r.Body)
    }
}

POST HTTP/1.1
Host : www.beego.cn
URL : http://www.beego.cn/api/demo?id=21&name=%E9%A9%AC%E8%B6%85
RawQuery : id=21&name=%E9%A9%AC%E8%B6%85
Content-Type : [text/plain; charset=UTF-8]
User-Agent : [Go-http-client/1.14]
Transfer-Encoding : [chunked]
Accept-Encoding : [gzip, deflate]
Authorization : [token_value]


Status : 200 OK
Server : [nginx/1.15.5]
Date : [Thu, 09 Apr 2020 15:26:56 GMT]
Content-Type : [application/json; charset=utf-8]
Content-Length : [54]
Connection : [keep-alive]


body: {
"method": "POST",
"name": "马超",
"id": 21
}


PUT测试请求

func main() {
    url := "http://www.beego.cn/api/demo"
    r, err = request.Put(url, request.Param{"id": 22, "name": "关羽"})
    if err == nil {
        r.Dump()
        fmt.Println("----------------------------------------------------")
        fmt.Println("body:", r.Body)
    }
}

PUT HTTP/1.1
Host : www.beego.cn
URL : http://www.beego.cn/api/demo?id=22&name=%E5%85%B3%E7%BE%BD
RawQuery : id=22&name=%E5%85%B3%E7%BE%BD
Accept-Encoding : [gzip, deflate]
Authorization : [token_value]
Content-Type : [text/plain; charset=UTF-8]
User-Agent : [Go-http-client/1.14]
Transfer-Encoding : [chunked]


Status : 200 OK
Content-Type : [application/json; charset=utf-8]
Content-Length : [53]
Connection : [keep-alive]
Server : [nginx/1.15.5]
Date : [Thu, 09 Apr 2020 15:26:56 GMT]


body: {
"method": "PUT",
"name": "关羽",
"id": 22
}


DELETE测试请求

func main() {
    url := "http://www.beego.cn/api/demo"
    r, err = request.Delete(url, request.Param{"id": 23, "name": "张飞"})
    if err == nil {
        r.Dump()
        fmt.Println("----------------------------------------------------")
        fmt.Println("body:", r.Body)
    }
}

DELETE HTTP/1.1
Host : www.beego.cn
URL : http://www.beego.cn/api/demo?id=23&name=%E5%BC%A0%E9%A3%9E
RawQuery : id=23&name=%E5%BC%A0%E9%A3%9E
Transfer-Encoding : [chunked]
Accept-Encoding : [gzip, deflate]
Authorization : [token_value]
Content-Type : [text/plain; charset=UTF-8]
User-Agent : [Go-http-client/1.14]


Status : 200 OK
Server : [nginx/1.15.5]
Date : [Thu, 09 Apr 2020 15:26:56 GMT]
Content-Type : [application/json; charset=utf-8]
Content-Length : [56]
Connection : [keep-alive]


body: {
"method": "DELETE",
"name": "张飞",
"id": 23
}


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:是个懒人

查看原文:Golang发送GET、POST、PUT、DELETE请求

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3453 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传