Parsing and building a URL
In many cases, it is better to manipulate a URL with the use of handy tools than trying to handle it as a simple string. Go standard libraries naturally contain the utilities to manipulate a URL. This recipe will go through some of these major functions.
How to do it...
- Open the console and create the folder
chapter07/recipe05. - Navigate to the directory.
- Create the
url.gofile with the following content:
package main
import (
"encoding/json"
"fmt"
"net/url"
)
func main() {
u := &url.URL{}
u.Scheme = "http"
u.Host = "localhost"
u.Path = "index.html"
u.RawQuery = "id=1&name=John"
u.User = url.UserPassword("admin", "1234")
fmt.Printf("Assembled URL:\n%v\n\n\n", u)
parsedURL, err := url.Parse(u.String())
if err != nil {
panic(err)
}
jsonURL, err := json.Marshal(parsedURL)
...