Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Get full hostname along with port from a URL in Go (Golang)

Posted on July 27, 2021July 27, 2021 by admin

Table of Contents

  • Overview
  • Program

Overview

net/url package of golang contains a Parse function that can be used to parse a given and return the URL instance of the URL structhttps://golang.org/pkg/net/url/#URL

Once the given URL is parsed correctly, then it will return the URI object. We can then access the below information from the URI

  • Scheme
  • User Info
  • Hostname
  • Port
  • Pathname
  • Query Params
  • Fragment

Once we have all the parts we can concatenate them to get the full hostname along with the port. We will parse the below URL

https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history

Then the full hostname along with port will be

https://golangbyexample.com:8000

Program

Below is the program for the same.

package main

import (
	"fmt"
	"log"
	"net/url"
)

func main() {
	input_url := "https://test:abcd123@golangbyexample.com:8000/tutorials/intro?type=advance&compact=false#history"
	u, err := url.Parse(input_url)
	if err != nil {
		log.Fatal(err)
	}

	fullHostname := u.Scheme + "://" + u.Host

	fmt.Println(fullHostname)
}

Output

https://golangbyexample.com:8000:8000
  • go
  • golang
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme