How to Parse and Manipulate URLs in Go

Web
Parse and manipulate URLs in Go using the net/url package to extract components like host and path.

Use the net/url package to parse URLs into structured components and manipulate them safely.

package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, _ := url.Parse("https://user:pass@example.com:8080/path?query=1#section")
	fmt.Println(u.Host)        // example.com:8080
	fmt.Println(u.Path)        // /path
	fmt.Println(u.RawQuery)    // query=1
	fmt.Println(u.Fragment)    // section
	
	// Manipulate
	u.Scheme = "http"
	u.Host = "newhost.com"
	fmt.Println(u.String())    // http://user:pass@newhost.com/path?query=1#section
}