美文网首页
Golang发送GET、POST、PUT、DELETE请求

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

作者: 懒人程序猿 | 来源:发表于2020-04-09 23:49 被阅读0次

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

    package requests
    
    import (
        "compress/gzip"
        "fmt"
        "io"
        "io/ioutil"
        "log"
        "net/http"
    )
    
    type Headers map[string]string
    
    type Cookies []*http.Cookie
    
    type Data map[string]interface{}
    
    // params
    type Params struct {
        Data Data
        Headers Headers
        Cookies Cookies
    }
    
    // debugger
    var Debugger bool = false
    
    // response
    type responses struct {
        Response *http.Response
        Body string
    }
    
    func request(method string, url string, params Params) (r responses, e error) {
        // 打印debugger发起请求
        printSendDebugger(method, url, params)
        r, e = do(method, url, params)
        if e != nil {
            return
        }
        // 打印debugger返回请求
        printResultDebugger(r)
        return
    }
    
    func do(method string, url string, params Params) (r responses, e error) {
        request, e := http.NewRequest(method, url, nil)
        // header
        addHeaders(request, params.Headers)
        // cookie
        addCookies(request, params.Cookies)
        // 参数
        addData(request, params.Data)
        r.Response, e = http.DefaultClient.Do(request)
        defer r.Response.Body.Close()
        if e != nil {
            return
        }
        unCoding(&r)
        return
    }
    
    func addHeaders(request *http.Request, headers Headers) {
        for k, v := range headers{
            request.Header.Add(k, v)
        }
    }
    
    // 添加cookie
    func addCookies(request *http.Request, cookies Cookies) {
        for _, v := range cookies{
            request.AddCookie(v)
        }
    }
    
    // 添加参数
    func addData(request *http.Request, data Data) {
        query := request.URL.Query()
        for k, v := range data{
            query.Add(k, fmt.Sprint(v))
        }
        request.URL.RawQuery = query.Encode()
    }
    
    func unCoding(r *responses) {
        if r.Response.StatusCode == 200 {
            switch r.Response.Header.Get("Content-Encoding") {
            case "gzip":
                reader, _ := gzip.NewReader(r.Response.Body)
                for {
                    buf := make([]byte, 1024)
                    n, err := reader.Read(buf)
                    if err != nil && err != io.EOF {
                        panic(err)
                    }
                    if n == 0 {
                        break
                    }
                    r.Body += string(buf)
                }
            default:
                bodyByte, _ := ioutil.ReadAll(r.Response.Body)
                r.Body = string(bodyByte)
            }
        } else {
            bodyByte, _ := ioutil.ReadAll(r.Response.Body)
            r.Body = string(bodyByte)
        }
    }
    
    // debugger发起请求
    func printSendDebugger(method string, url string, params Params) {
        if Debugger {
            log.Println("debug log start ----------")
            fmt.Println("Method", method)
            fmt.Println("Host", ":", url)
            for k, v := range params.Headers{
                fmt.Println(k, ":", v)
            }
            fmt.Println("----------------------------------------------------")
        }
    }
    
    func printResultDebugger(r responses) {
        if Debugger {
            fmt.Println("Status", ":", r.Response.Status)
            for key, val := range r.Response.Header {
                fmt.Println(key, ":", val[0])
            }
            log.Println("debug log end ----------")
        }
    }
    
    // request
    func Request(method string, url string, params Params) (responses, error) {
        return request(method, url , params)
    }
    
    // get
    func Get(url string, params Params) (responses, error) {
        return request("GET", url , params)
    }
    
    // post
    func Post(url string, params Params) (responses, error) {
        return request("POST", url , params)
    }
    
    // put
    func Put(url string, params Params) (responses, error) {
        return request("PUT", url , params)
    }
    
    // delete
    func Delete(url string, params Params) (responses, error) {
        return request("DELETE", url , params)
    }
    
    
    
    
    

    测试请求

    func main() {
        requests.Debugger = true
        var params requests.Params
        params.Data = requests.Data{
            "id": 100000,
            "name": "赵云",
            "sid": 10,
        }
        params.Cookies = requests.Cookies{
            {Name: "id", Value: "1"},
            {Name: "name", Value: "zhaoyun"},
            {Name: "sid", Value: "10"},
        }
        params.Headers = requests.Headers{
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36",
            "Content-Type": "text/plain; charset=UTF-8",
            "Transfer-Encoding": "chunked",
            "Accept-Encoding": "gzip, deflate",
            "Authorization": "",
        }
        r, e := requests.Request("GET", "https://www.demo.com/demo.php", params)
        if e != nil {
            fmt.Println(e)
            os.Exit(0)
        }
        fmt.Println(r.Body)
    }
    
    image.png

    相关文章

      网友评论

          本文标题:Golang发送GET、POST、PUT、DELETE请求

          本文链接:https://www.haomeiwen.com/subject/kgmkmhtx.html