P
P
prr133f2022-04-11 20:18:50
API
prr133f, 2022-04-11 20:18:50

How to add headers to http request using golang?

Hello, I rummaged through a bunch of articles on the Internet and read the documentation for the net/http package several times, is it possible to add a header to the http get request with it, or with the help of another package?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2022-04-11
@prr133f

More or less like this

func makeRequest() error {
  req, err := http.NewRequest(http.MethodGet, "https://habr.com", nil)
  if err != nil {
    return err
  }

  req.Header.Add("User-Agent", "mySuperTestApp v1.0")

  res, err := http.DefaultClient.Do(req)
  if err != nil {
    return err
  }
  defer res.Body.Close()
  if res.StatusCode != http.StatusOK {
    return fmt.Errorf("wrong status code: %d", res.StatusCode)
  }

  body, err := io.ReadAll(res.Body)
  if err != nil {
    return err
  }

  fmt.Println(string(body))
  return nil
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question