Mastering Go’s net/url: Essential Functions and Practical Examples
This article provides a comprehensive guide to Go's net/url package, explaining key functions such as PathEscape, QueryEscape, Parse, and ResolveReference, and illustrating their usage with clear code snippets that demonstrate URL parsing, encoding, decoding, and manipulation in real-world scenarios.
This note records the author's study of Go's standard library net/url.
func PathEscape
func PathEscape(s string) stringPathEscape escapes a string so it can be safely placed in a URL path segment.
func PathUnescape
func PathUnescape(s string) (string, error)PathUnescape performs the inverse of PathEscape, converting %AB back to byte 0xAB; it returns an error if a % is not followed by two hexadecimal digits.
func QueryEscape
func QueryEscape(s string) stringQueryEscape encodes s so it can be safely used in a URL query.
func QueryUnescape
func QueryUnescape(s string) (string, error)QueryUnescape reverses QueryEscape, converting %AB to byte 0xAB and '+' to a space, returning an error on malformed percent‑escapes.
Example:
package main
import (
"fmt"
"encoding/base64"
"net/url"
"crypto/rand"
"io"
"log"
)
// sessionId generates a unique session identifier.
func sessionId() string {
b := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, b); err != nil {
return ""
}
fmt.Println(b)
return base64.URLEncoding.EncodeToString(b)
}
func main() {
sessionId := sessionId()
fmt.Println(sessionId)
encodedSessionId := url.QueryEscape(sessionId)
fmt.Println(encodedSessionId)
decodedSessionId, err := url.QueryUnescape(encodedSessionId)
if err != nil {
log.Fatal(err)
}
fmt.Println(decodedSessionId)
}type URL
type URL struct {
Scheme string // protocol scheme
Opaque string // encoded opaque data
User *Userinfo // username and password information
Host string // host or host:port
Path string // path, slash‑separated
RawQuery string // encoded query string, without '?'
Fragment string // fragment identifier, without '#'
}A URL represents a parsed URL reference. The basic format is:
scheme:[//[userinfo@]host/path[?query][#fragment]]When the scheme is not followed by "://", the format is:
scheme:opaque[?query][#fragment]func Parse
func Parse(rawurl string) (url *URL, err error)Parse parses rawurl into a URL structure; rawurl may be absolute or relative.
func ParseRequestURI
func ParseRequestURI(rawurl string) (url *URL, err error)ParseRequestURI parses rawurl assuming it appears in an HTTP request, treating it as an absolute URL or absolute path and ignoring any fragment.
func (*URL) IsAbs
func (u *URL) IsAbs() boolIsAbs returns true only if the URL is absolute.
func (*URL) Query
func (u *URL) Query() ValuesQuery parses the RawQuery field and returns the corresponding Values map.
func (*URL) RequestURI
func (u *URL) RequestURI() stringRequestURI returns the encoded path?query or opaque?query string for use in HTTP requests.
func (*URL) String
func (u *URL) String() stringString reconstructs a valid URL string from the URL struct, using either the opaque or hierarchical form.
func (*URL) EscapedPath
func (u *URL) EscapedPath() stringEscapedPath returns the escaped form of u.Path, computing it if RawPath is empty.
func (*URL) Hostname
func (u *URL) Hostname() stringHostname returns u.Host without any port number.
func (*URL) Port
func (u *URL) Port() stringPort returns the port part of u.Host, without the leading colon.
func (*URL) Parse
func (u *URL) Parse(ref string) (*URL, error)Parse resolves ref (absolute or relative) against u, returning a new URL.
func (*URL) ResolveReference
func (u *URL) ResolveReference(ref *URL) *URLResolveReference resolves a reference URL against u according to RFC 3986 §5.2, always returning a new URL instance.
func (*URL) MarshalBinary
func (u *URL) MarshalBinary() (text []byte, err error)MarshalBinary converts the URL to its binary representation.
func (*URL) UnmarshalBinary
func (u *URL) UnmarshalBinary(text []byte) errorUnmarshalBinary parses a binary URL representation back into a URL struct.
type Userinfo
type Userinfo struct { /* unexported fields */ }Userinfo encapsulates username and password details of a URL.
func User
func User(username string) *UserinfoUser returns a Userinfo with the given username and no password.
func UserPassword
func UserPassword(username, password string) *UserinfoUserPassword returns a Userinfo with both username and password (use with caution).
func (Userinfo) Username
func (u *Userinfo) Username() stringUsername returns the username.
func (Userinfo) Password
func (u *Userinfo) Password() (string, bool)Password returns the password and a boolean indicating if a password is set.
func (Userinfo) String
func (u *Userinfo) String() stringString returns the encoded user information in the form "username[:password]".
type Values
type Values map[string][]stringValues maps keys to a list of values, commonly used for query parameters and form data.
func ParseQuery
func ParseQuery(query string) (m Values, err error)ParseQuery parses a URL‑encoded query string into a Values map.
func (Values) Get
func (v Values) Get(key string) stringGet returns the first value associated with the given key.
func (Values) Set
func (v Values) Set(key, value string)Set replaces any existing values for key with a single value.
func (Values) Add
func (v Values) Add(key, value string)Add appends a value to the list for the given key.
func (Values) Del
func (v Values) Del(key string)Del deletes the values associated with key.
func (Values) Encode
func (v Values) Encode() stringEncode returns the URL‑encoded form of the values, sorted by key.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
