Go实现get和post请求
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2019-11-14 19:59:09
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
自动切换get/post
package main import ( "fmt" "io/ioutil" "net/http" "net/url" "time" // "reflect" "net" "regexp" "strings" // "net/http/cookiejar" ) func sendRequest(conf map[string]string) string { req := map[string]string{} req["url"] = "" req["requestHeader"] = "" req["postdata"] = "" req["post"] = "0" // 代理 my***xy:a****l@127.0.0.1:8080 req["proxy"] = "" for k, v := range conf { req[k] = v } var proxy func(*http.Request) (*url.URL, error) = nil if req["proxy"] != "" { proxy = func(_ *http.Request) (*url.URL, error) { return url.Parse("http://" + req["proxy"]) } } transport := &http.Transport{ Proxy: proxy, Dial: func(netw, addr string) (net.Conn, error) { conn, err := net.DialTimeout(netw, addr, time.Second*2) //设置建立连接超时 if err != nil { return nil, err } conn.SetDeadline(time.Now().Add(time.Second * 2)) //设置发送接受数据超时 return conn, nil }, ResponseHeaderTimeout: time.Second * 2, } //初始化配置参数 client := &http.Client{ // Jar CookieJar // CheckRedirect func(req *Request, via []*Request) error Timeout: 10 * time.Second, Transport: transport, } // client := &http.Client{} //提交请求 method := "GET" if req["post"] != "0" || req["postdata"] != "" { method = "POST" } reqest, err := http.NewRequest(method, req["url"], strings.NewReader(req["postdata"])) if method == "POST" { reqest.Header.Add("Content-Type", "application/x-www-form-urlencoded") } // 增加header选项 if req["requestHeader"] != "" { re := regexp.MustCompile(`\r?\n`) arr := re.Split(req["requestHeader"], -1) for _, v := range arr { v = strings.TrimSpace(v) pos := strings.Index(v, ":") if pos == -1 { continue } if pos == 0 { pos2 := strings.Index(v[1:], ":") reqest.Header.Add(v[:pos2+1], v[pos2+2:]) } else { reqest.Header.Add(v[:pos], v[pos+1:]) } } } if err != nil { panic(err) } //处理返回结果 response, err := client.Do(reqest) if err != nil { return err.Error() } defer response.Body.Close() // status := response.StatusCode respByte, _ := ioutil.ReadAll(response.Body) return string(respByte) } func main() { req := map[string]string{} req["url"] = "https://www.baidu.com" req["requestHeader"] = `` // req["proxy"] = "m#####xy:ad####3l@127.0.0.1:8880" fmt.Println(sendRequest(req)) //fmt.Scan() // fmt.Println(reflect.TypeOf(req)) }