Get Query string as it is passed

时间:2018-07-24 10:18:54

标签: url go

I'm new to Go. My question is how to get URL encoded string on stdout.

Below is the URL string I am using to hit an api.

schooltubeapi/v1/channeldetails?channelName=long%20division%20.

Below is the code that I am using to get RawQuery

url1 := ChannelName
u, _ := url.Parse(url1)
log.Println(u)
u.RawQuery = u.Query().Encode()
log.Println(u)

[Output]

long division

[Expected]

long%20division%20

I have searched alot But cannot found a similar problem with a solution.

1 个答案:

答案 0 :(得分:0)

For url encoded string use URL struct of url package to get RawQuery as passed in the URI:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    stringValue := "long division "
    t := &url.URL{Path: stringValue}
    encodedString := t.String()
    fmt.Println(encodedString)
}

Playground Example

In Golang spec for URL. It is stated:-

that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. A consequence is that it is impossible to tell which slashes in the Path were slashes in the raw URL and which were %2f. This distinction is rarely important, but when it is, code must not use Path directly. The Parse function sets both Path and RawPath in the URL it returns, and URL's String method uses RawPath if it is a valid encoding of Path, by calling the EscapedPath method.

type URL struct {
        Scheme     string
        Opaque     string    // encoded opaque data
        User       *Userinfo // username and password information
        Host       string    // host or host:port
        Path       string    // path (relative paths may omit leading slash)
        RawPath    string    // encoded path hint (see EscapedPath method)
        ForceQuery bool      // append a query ('?') even if RawQuery is empty
        RawQuery   string    // encoded query values, without '?'
        Fragment   string    // fragment for references, without '#'
}

For more information Check Golang spec for URL