Vitalii
Vitalii

Reputation: 11071

Add query string url in Go

I need to send http request to https://some-domain.com/getsomething/?id=myID I have url and need to add to it a query parameter. Here is my Go code

baseUrl := "https://some-domain.com"
relativeUrl := "/getsomething/"
url, _ := url.Parse(baseUrl)
url.Path = path.Join(url.Path, relativeUrl)

// add parameter to query string
queryString := url.Query()
queryString.Set("id", "1")
// add query to url
url.RawQuery = queryString.Encode()
// print it 
fmt.Println(url.String())

In output I see this url: https://some-domain.com/getsomething?id=1

And this one is required: https://some-domain.com/getsomething/?id=1

You can see that there is no / character before ?.

Do you know how to fix it without manual string manipulations?

https://play.golang.org/p/HsiTzHcvlQ

Upvotes: 6

Views: 9226

Answers (1)

s7anley
s7anley

Reputation: 2498

You can use ResolveReference.

package main

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

func main() {
    relativeUrl := "/getsomething/"
    u, err := url.Parse(relativeUrl)
    if err != nil {
        log.Fatal(err)
    }

    queryString := u.Query()
    queryString.Set("id", "1")
    u.RawQuery = queryString.Encode()

    baseUrl := "https://some-domain.com"
    base, err := url.Parse(baseUrl)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(base.ResolveReference(u))
}

https://play.golang.org/p/BIU29R_XBM

Upvotes: 11

Related Questions