Go执行网络请求

1 发送get请求

func http_get(url string) string {
  resp, err := http.Get(url)
  if err != nil {
    fmt.Println(err)
    return ""
  }
  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  // resp.StatusCode
  return string(body)
}

2 发送get请求带参数

import (
  "fmt"
  "io/ioutil"
  "net/http"
  "net/url"
)

func http_get(uurl string) string {

  Url, err := url.Parse("http://httpbin.org/get")
  if err != nil {
    return ""
  }
  params := url.Values{}
  params.Set("key1", "val1")
  params.Set("key2", "val2")
  Url.RawQuery = params.Encode()
  urlPath := Url.String()

  resp, err := http.Get(urlPath)
  if err != nil {
    fmt.Println(err)
    return ""
  }
  defer resp.Body.Close()
  body, err := ioutil.ReadAll(resp.Body)
  // resp.StatusCode
  return string(body)
}

3 Basic Auth

...

client := http.Client{Timeout: 5 * time.Second}

  req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
  if err != nil {
    log.Fatal(err)
  }

  req.SetBasicAuth(USER, PASS)

  resp, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return ""
  }

...

 

4

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *