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