Master Go’s net/url: URL Parsing, Escaping, and Query Handling Explained

This article provides a comprehensive guide to Go's net/url package, covering import methods, key functions like PathEscape, PathUnescape, QueryEscape, QueryUnescape, as well as the URL type fields and methods such as Parse, ResolveReference, and utilities for query manipulation, all illustrated with practical code examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Go’s net/url: URL Parsing, Escaping, and Query Handling Explained

Import the net/url package to work with URLs in Go.

func PathEscape

func PathEscape(s string) string

PathEscape escapes a string so it can be safely placed in a URL path segment.

func PathUnescape

func PathUnescape(s string) (string, error)

PathUnescape reverses PathEscape, converting %AB sequences back to the corresponding byte. It returns an error if any % is not followed by two hexadecimal digits. Unlike QueryUnescape, it does not convert '+' to a space.

func QueryEscape

func QueryEscape(s string) string

QueryEscape encodes a string so it can be safely used in a URL query.

func QueryUnescape

func QueryUnescape(s string) (string, error)

QueryUnescape decodes a string previously encoded with QueryEscape, converting %AB to the corresponding byte and '+' to a space. It returns an error for malformed percent‑encodings.

type URL

type URL struct {
    Scheme   string
    Opaque   string
    User     *Userinfo
    Host     string
    Path     string
    RawQuery string
    Fragment string
}

The URL type represents a parsed URL. Its basic format is scheme://[userinfo@]host/path[?query][#fragment]. If the scheme is not followed by "//", the format is scheme:opaque[?query][#fragment].

func Parse

func Parse(rawurl string) (*URL, error)

Parse converts a raw URL string into a URL struct. The input can be an absolute or relative URL.

func ParseRequestURI

func ParseRequestURI(rawurl string) (*URL, error)

ParseRequestURI parses a raw URL assuming it appears in an HTTP request; it treats the input as an absolute URL or absolute path and ignores any fragment.

func (*URL) IsAbs

func (u *URL) IsAbs() bool

IsAbs reports whether the URL is absolute.

func (*URL) Query

func (u *URL) Query() Values

Query parses the RawQuery field and returns a Values map of key‑value pairs.

func (*URL) RequestURI

func (u *URL) RequestURI() string

RequestURI returns the encoded path?query or opaque?query string suitable for HTTP requests.

func (*URL) String

func (u *URL) String() string

String reconstructs the URL into a valid URL string, using either the opaque or hierarchical form depending on whether Opaque is set.

func (*URL) EscapedPath

func (u *URL) EscapedPath() string

EscapedPath returns the escaped form of Path. If RawPath is valid, it is returned; otherwise the method computes an escaped version.

func (*URL) Hostname

func (u *URL) Hostname() string

Hostname returns the host part of the URL without any port.

func (*URL) Port

func (u *URL) Port() string

Port returns the port part of the host, without the leading colon.

func (*URL) ResolveReference

func (u *URL) ResolveReference(ref *URL) *URL

ResolveReference resolves a reference URL (absolute or relative) against the base URL, returning a new absolute URL.

func (*URL) MarshalBinary / UnmarshalBinary

func (u *URL) MarshalBinary() (text []byte, err error)
func (u *URL) UnmarshalBinary(text []byte) error

These methods convert a URL to and from its binary representation.

type Userinfo

type Userinfo struct { /* hidden fields */ }

Userinfo encapsulates username and optional password information for a URL.

func User / UserPassword

func User(username string) *Userinfo
func UserPassword(username, password string) *Userinfo

These functions create Userinfo values with or without a password.

func (*Userinfo) Username / Password / String

func (u *Userinfo) Username() string
func (u *Userinfo) Password() (string, bool)
func (u *Userinfo) String() string

Username returns the username; Password returns the password and a boolean indicating its presence; String returns the encoded "username[:password]" representation.

type Values

type Values map[string][]string

Values maps string keys to slices of strings and is used for query parameters and form values.

func ParseQuery

func ParseQuery(query string) (Values, error)

ParseQuery parses a URL‑encoded query string into a Values map.

func (Values) Get / Set / Add / Del / Encode

func (v Values) Get(key string) string
func (v Values) Set(key, value string)
func (v Values) Add(key, value string)
func (v Values) Del(key string)
func (v Values) Encode() string

These methods provide convenient manipulation of query parameters.

Example: Encoding and Decoding a Session ID

package main
import (
    "fmt"
    "encoding/base64"
    "crypto/rand"
    "io"
    "log"
    "net/url"
)

func sessionId() string {
    b := make([]byte, 32)
    if _, err := io.ReadFull(rand.Reader, b); err != nil {
        return ""
    }
    return base64.URLEncoding.EncodeToString(b)
}

func main() {
    id := sessionId()
    fmt.Println(id)
    enc := url.QueryEscape(id)
    fmt.Println(enc)
    dec, err := url.QueryUnescape(enc)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(dec)
}

This example demonstrates generating a random session ID, encoding it for safe inclusion in a URL query, and decoding it back.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendGoqueryURL parsingescapingnet/url
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.