Skip to main content

port.go

port.go - Overview

  1. Overview

This file provides a utility function to extract the port number from a network address.

  1. Detailed Documentation

Function: GetPort

  • Purpose: Extracts the port number from a net.Addr interface.
  • Parameters:
    • addr (net.Addr): The network address from which to extract the port.
  • Returns:
    • (int, error): The port number as an integer and an error if any occurred during the process. Returns -1 for the port number in case of an error.
  1. Code Examples
package main

import (
"fmt"
"net"
"strconv" // Import the "strconv" package
)

// GetPort returns the port of an endpoint address.
func GetPort(addr net.Addr) (int, error) {
_, port, err := net.SplitHostPort(addr.String())
if err != nil {
return -1, err
}

parsedPort, err := strconv.Atoi(port)
if err != nil {
return -1, err
}

return parsedPort, nil
}

func main() {
// Example Usage:
addr, err := net.ResolveTCPAddr("tcp", "localhost:8080")
if err != nil {
fmt.Println("Error resolving address:", err)
return
}

port, err := GetPort(addr)
if err != nil {
fmt.Println("Error getting port:", err)
return
}

fmt.Println("Port:", port)
}

Include in Getting Started: NO