Go语言封装Http协议GET和POST请求

作者: Golang语言社区 | 来源:发表于2019-01-02 06:36 被阅读38次
    /*
    有关Http协议GET和POST请求的封装
    */
    package net
    
    import (
        "net/http"
        "io"
        "bytes"
        "encoding/json"
        "io/ioutil"
        "time"
    )
    
    //发送GET请求
    //url:请求地址
    //response:请求返回的内容
    func Get(url string) (response string) {
        client := http.Client{Timeout: 5 * time.Second}
        resp, error := client.Get(url)
        defer resp.Body.Close()
        if error != nil {
            panic(error)
        }
    
        var buffer [512]byte
        result := bytes.NewBuffer(nil)
        for {
            n, err := resp.Body.Read(buffer[0:])
            result.Write(buffer[0:n])
            if err != nil && err == io.EOF {
                break
            } else if err != nil {
                panic(err)
            }
        }
    
        response = result.String()
        return
    }
    
    //发送POST请求
    //url:请求地址,data:POST请求提交的数据,contentType:请求体格式,如:application/json
    //content:请求放回的内容
    func Post(url string, data interface{}, contentType string) (content string) {
        jsonStr, _ := json.Marshal(data)
        req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
        req.Header.Add("content-type", contentType)
        if err != nil {
            panic(err)
        }
        defer req.Body.Close()
    
        client := &http.Client{Timeout: 5 * time.Second}
        resp, error := client.Do(req)
        if error != nil {
            panic(error)
        }
        defer resp.Body.Close()
    
        result, _ := ioutil.ReadAll(resp.Body)
        content = string(result)
        return
    }
    

    社区交流群:221273219
    Golang语言社区论坛 :
    www.Golang.Ltd
    LollipopGo游戏服务器地址:
    https://github.com/Golangltd/LollipopGo
    社区视频课程课件GIT地址:
    https://github.com/Golangltd/codeclass


    Golang语言社区

    相关文章

      网友评论

        本文标题:Go语言封装Http协议GET和POST请求

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