[Golang] HTTP Request With Custom User-Agent


Example of HTTP request with custom User-Agent header via Go standard net/http package.

package main

import (
      "errors"
      "io/ioutil"
      "net/http"
      "strconv"
)

func HTTPRequestCustomUserAgent(url, userAgent string) (b []byte, err error) {
      req, err := http.NewRequest("GET", url, nil)
      if err != nil {
              return
      }

      req.Header.Set("User-Agent", userAgent)

      client := &http.Client{}
      resp, err := client.Do(req)
      if err != nil {
              return
      }
      defer resp.Body.Close()

      if resp.StatusCode != 200 {
              err = errors.New(
                      "resp.StatusCode: " +
                              strconv.Itoa(resp.StatusCode))
              return
      }

      return ioutil.ReadAll(resp.Body)
}

func main() {
      b, err := HTTPRequestCustomUserAgent("https://www.google.com/", "My User-Agent")
      if err != nil {
              panic(err)
      }
      println(string(b))
}

If you want to know how to send HTTP request with cookies, please see [2].


Tested on: Ubuntu Linux 17.10, Go 1.10.


References:

[1]GitHub - siongui/instago: Get photos, videos, stories, following and followers of Instagram
[2][Golang] HTTP Request With Cookies