unknwon/the-way-to-go_ZH_CN · error

usage: host port

Error message

usage: host port

What it means

Usage guard at the top of the simple TCP server main (section 15.1): after flag.Parse(), if flag.NArg() != 2 the program panics with 'usage: host port', demanding exactly two positional arguments (host and port) that are later combined with fmt.Sprintf("%s:%s", flag.Arg(0), flag.Arg(1)).

Source

Thrown at eBook/15.1.md:229

示例 15.5 [simple_tcp_server.go](examples/chapter_15/simple_tcp_server.go):

```go
// Simple multi-thread/multi-core TCP server.
package main

import (
	"flag"
	"fmt"
	"net"
	"os"
)

const maxRead = 25

func main() {
	flag.Parse()
	if flag.NArg() != 2 {
		panic("usage: host port")
	}
	hostAndPort := fmt.Sprintf("%s:%s", flag.Arg(0), flag.Arg(1))
	listener := initServer(hostAndPort)
	for {
		conn, err := listener.Accept()
		checkError(err, "Accept: ")
		go connectionHandler(conn)
	}
}

func initServer(hostAndPort string) *net.TCPListener {
	serverAddr, err := net.ResolveTCPAddr("tcp", hostAndPort)
	checkError(err, "Resolving address:port failed: '"+hostAndPort+"'")
	listener, err := net.ListenTCP("tcp", serverAddr)
	checkError(err, "ListenTCP: ")
	println("Listening to: ", listener.Addr().String())
	return listener
}

View on GitHub (pinned to 7a54d34d36)

Solutions

  1. Run with both arguments: go run simple_tcp_server.go localhost 5000
  2. Replace the panic with flag.Usage() plus log.Fatalf("usage: %s host port", os.Args[0]) for a proper usage message and exit code
  3. Define host/port as flag.String with sensible defaults so missing args fall back instead of aborting
  4. Validate that the port is numeric before passing it to net.ResolveTCPAddr

Example fix

// before
if flag.NArg() != 2 {
    panic("usage: host port")
}

// after
if flag.NArg() != 2 {
    flag.Usage()
    log.Fatalf("usage: %s host port", os.Args[0])
}
Defensive patterns

Strategy: validation

Validate before calling

// check invocation before anything touches the network
host, portStr, ok := os.Args[1], "", len(os.Args) == 3
if !ok {
    fmt.Fprintf(os.Stderr, "usage: %s host port\n", os.Args[0])
    os.Exit(2)
}
if _, err := strconv.Atoi(os.Args[2]); err != nil {
    fmt.Fprintf(os.Stderr, "port must be numeric: %s\n", os.Args[2])
    os.Exit(2)
}

Prevention

When it happens

Trigger: Running the binary with zero, one, or three-plus positional arguments — e.g. a plain 'go run simple_tcp_server.go' with nothing after the file, or flags that shift the positional count away from 2.

Common situations: First run from an IDE whose run configuration has no program arguments; forgetting the port; copying an invocation line from docs that used a different argument layout.

Related errors


AI-assisted analysis of unknwon/the-way-to-go_ZH_CN@7a54d34d36 (2026-08-15). Data as JSON: /api/errors/8c3bc50474b04f69. Report an issue: GitHub.