Master Go’s net/url: Parse, Build, and Manipulate URLs with Ease
This guide explores Go’s net/url package, demonstrating how to parse URLs, construct them programmatically, manipulate query strings, and safely escape or unescape characters, with clear code examples for each operation, making network development tasks simpler.
Go’s net/url package in the standard library offers powerful and flexible tools for handling URLs, covering parsing, building, query string manipulation, and escaping.
Parsing URLs
Use url.Parse to convert a URL string into a url.URL struct, then access components such as Scheme, Host, Path, and RawQuery.
u, err := url.Parse("https://example.com/path?query=123")
if err != nil {
log.Fatal(err)
}
fmt.Println("Scheme:", u.Scheme)
fmt.Println("Host:", u.Host)
fmt.Println("Path:", u.Path)
fmt.Println("Query string:", u.RawQuery)Building URLs
Populate a url.URL struct and call its String method to generate a properly encoded URL.
u := &url.URL{
Scheme: "https",
Host: "example.com",
Path: "search",
RawQuery: "query=go",
}
fmt.Println(u.String()) // https://example.com/search?query=goQuery String Handling
The url.Values type (a map[string][]string alias) simplifies building and parsing query strings.
values := url.Values{}
values.Add("name", "John")
values.Add("age", "30")
queryString := values.Encode() // age=30&name=John
fmt.Println(queryString)
values, _ = url.ParseQuery(queryString)
fmt.Println(values.Get("name")) // JohnEscaping and Unescaping
Use url.QueryEscape and url.QueryUnescape to safely encode or decode special characters in query components.
escaped := url.QueryEscape("name=John Doe&age=30")
fmt.Println(escaped) // name%3DJohn+Doe%26age%3D30
unescaped, _ := url.QueryUnescape(escaped)
fmt.Println(unescaped) // name=John Doe&age=30Conclusion
The net/url package is a versatile tool for Go developers, providing concise solutions for parsing, constructing, and manipulating URLs, as well as handling query strings and character escaping, thereby streamlining network programming tasks.
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.
Ops Development & AI Practice
DevSecOps engineer sharing experiences and insights on AI, Web3, and Claude code development. Aims to help solve technical challenges, improve development efficiency, and grow through community interaction. Feel free to comment and discuss.
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.
