okaryo.log

Sending a GET request with query parameters in Go | okaryo.log

Sending a GET request with query parameters in Go

    #Go

Introduction

When I wanted to send a GET request with query parameters using Go’s net/http package, I didn’t want to go through the hassle of manually constructing the parameters by appending ? and &.

Looking through the official API documentation to see if there was a better way, I found an efficient method which I’d like to summarize here.

Method

Instead of treating the URL as a mere string, it’s better to handle it as a URL object from net/url. Using this object, you can use the Query() method to conveniently add parameters.

package main

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

func main() {
  // Creating a URL object
  u, err := url.Parse("https://example.com/hoge")
  if err != nil {
    // handle error
  }

  // Adding query parameters
  q := u.Query()
  q.Set("key1", "value1")
  q.Set("key2", "value2")
  u.RawQuery = q.Encode()

  // Sending a GET request
  res, err := http.Get(u.String())
  if err != nil {
    // handle error
  }
  defer res.Body.Close()
}

Details

The Query() method returns a value of the Values type, which is defined as a map, as shown below:

type Values map[string][]string

You can add parameters to this map using the Set(key, value string) method. After setting your parameters, you encode them and set them as the query parameters for the URL object.

q.Set("key1", "value1")
q.Set("key2", "value2")
u.RawQuery = q.Encode()

References


Related Posts

No related posts

Related Posts
Promotion

This site uses Google Analytics.