如何在Go中获取URL

I tried looking it up, but couldn't find an already answered question.

How do I get the host part of the URL in Go?

For eg.

if the user enters http://localhost:8080 in the address bar, I wanted to extract "localhost" from the URL.

Go has built in library that can do it for you.

package main
import "fmt"
import "net"
import "net/url"
func main() {
    s := "http://localhost:8080"

    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    host, _, _ := net.SplitHostPort(u.Host)
    fmt.Println(host)
}

https://golang.org/pkg/net/url/#

If you are talking about extracting the host from a *http.Request you can do the following:

func ExampleHander(w http.ResponseWriter, r *http.Request) { host := r.Host // This is your host (and will include port if specified) }

If you just want to access the host part without the port part you can do the following:

func ExampleHandler(w http.ResponseWriter, r *http.Request) { host, port, _ := net.SplitHostPort(r.Host) }

For the last one to work you also have to import net

Go has wonderful documentation, I would also recommend taking a look at that: net/http