6

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

3
  • Everything is ok with this code, for me the output is https://some-domain.com/getsomething/?id=1. I have edited your code, because the Set function takes a string as a value. Commented Sep 13, 2017 at 11:41
  • I tried your program, and the output is as you require (https://some-domain.com/getsomething/?id=1). on Playground - play.golang.org/p/M87JQqFb45 Commented Sep 13, 2017 at 11:42
  • I'm sorry, I made my code in this question more simple. Updated. Commented Sep 13, 2017 at 11:55

1 Answer 1

11

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yop, my bad. Updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.