URL Parsing in Go
Go: URL Parsing
Go's
net/url
package provides functionality for parsing URLs and working with their components. The package includes a URL type representing a parsed URL, and functions for parsing and building URLs.
How to parse a URL in Go
package main
import (
"fmt"
"net/url"
)
func main() {
str := "https://www.example.com/path?query=value#fragment"
parsedUrl, err := url.Parse(str)
if err != nil {
fmt.Println("Failed to parse URL:", err)
return
}
fmt.Println(parsedUrl.Scheme) // Output: https
fmt.Println(parsedUrl.Host) // Output: www.example.com
fmt.Println(parsedUrl.Path) // Output: /path
fmt.Println(parsedUrl.RawQuery) // Output: query=value
fmt.Println(parsedUrl.Fragment) // Output: fragment
}
In this example, the url.Parse()
function is used to parse the URL string https://www.example.com/path?query=value#fragment
. The function returns two values: a URL
struct representing the parsed URL, and an error if the string could not be parsed.
You can then access the components of the parsed URL using the fields of the URL
struct, such as Scheme
, Host
, Path
, RawQuery
, and Fragment
.
Here are some other functions you can use for working with URLs in Go:
url.QueryEscape(s string) string
: escapes a string so it can be safely placed inside a URL query parameter.url.QueryUnescape(s string) (string, error)
: unescapes a string previously escaped by url.QueryEscape().url.Values
: a type representing URL query parameters as key-value pairs. You can use theGet()
,Set()
, andAdd()
methods to manipulate query parameters.url.ParseRequestURI(s string) (*url.URL, error)
: parses a URI as if it were a request URL, without a leading slash.
Note that the net/url
package only handles parsing and manipulation of the URL string itself. If you need to actually make HTTP requests or work with web servers, you should use the net/http
package.
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go