How to extract base url using golang?

Member

by gilbert , in category: Third Party Scripts , 17 days ago

How to extract base url using golang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by herminia_bruen , 16 days ago

@gilbert 

You can extract the base URL from a given URL string using the net/url package in Go. Here is an example code snippet that demonstrates how to extract the base URL:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
	"fmt"
	"net/url"
)

func main() {
	u, err := url.Parse("https://www.example.com/path/to/page")
	if err != nil {
		fmt.Println("Error parsing URL:", err)
		return
	}

	baseURL := &url.URL{
		Scheme: u.Scheme,
		Host:   u.Host,
	}
	fmt.Println("Base URL:", baseURL.String())
}


In this code snippet, we first parse the input URL string using url.Parse() function. Then, we create a new url.URL struct with the scheme and host extracted from the parsed URL. Finally, we print out the base URL by calling String() method on the baseURL.


You can replace the input URL string with any URL that you want to extract the base URL from.