golang的GET請求(類似於PHP的CURL)


 

check_url := "https://www.baidu.com"

    header := make(map[string]string)

    res, err := util.Hpool.Request(check_url, http.MethodGet, "", header) if err != nil {
        return nil, err
    }

    
    spew.Dump(res)

 

【http.go】

package util

import (
    "bytes"
    "io/ioutil"
    "net/http"
    "time"
)

type HttpConPool struct {
    Conn *http.Client
}

var Hpool *HttpConPool

func loadHttpPool() {
    Hpool = new(HttpConPool)
    Hpool.Conn = &http.Client{
        Transport: &http.Transport{
            MaxIdleConnsPerHost: Str2Int(GetConfigValue("http", "max_conn")),
        },
        Timeout: time.Duration(Str2Int(GetConfigValue("http", "timeout"))) * time.Millisecond,
    }
}

func (h *HttpConPool) Request(url string, method string, data string, header map[string]string) (interface{}, error) {
    req, err := http.NewRequest(method, url, bytes.NewBuffer([]byte(data)))
    if err != nil {
        return nil, err
    }

    for h, v := range header {
        req.Header.Set(h, v)
    }

    response, err := h.Conn.Do(req)

    if err != nil {
        return nil, err
    } else if response != nil {
        defer response.Body.Close()

        r_body, err := ioutil.ReadAll(response.Body)
        if err != nil {
            return nil, err
        } else {
            return string(r_body), nil
        }
    } else {
        return nil, nil
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM