Menu Close

Go – JoinHostPort() function in net package in go

Here, We will learnĀ how to combine host and port number to form a network address in go. We can do it by using JoinHostPort() function in net package in go.

Function prototype:

func JoinHostPort(host, port string) string

Return value:

JoinHostPort() function in net package in go 
returns network address by combining host
and port number like "host:port".
If host has ipv6 address then it combines like
"[host]:port".

Example with code:

package main

import (
  "fmt"
  "net"
)

func main() {

  s := net.JoinHostPort("10.10.10.10", "9900")
  fmt.Println(s)

  s = net.JoinHostPort("2001:db8:85a3:0:0:8a2e:370:7334", "9900")
  fmt.Println(s)

}

Output:

10.10.10.10:9900
[2001:db8:85a3:0:0:8a2e:370:7334]:9900

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, net, packages

Leave a Reply

Your email address will not be published.

Contact Us