luminyra

Quickstart

Parse a port and validate its range in a single Result chain.

Run the port example

Use Go 1.27 or later. Install fp in your module, copy the complete example to main.go, and run go run .. From the fp source directory, you can also run go run ./examples/result.

go get github.com/luminyra/fp
Complete port example
// Command result chains ordinary (value, error) functions with fp.Result and
// recovers from or annotates a failure.
package main

import (
	"fmt"
	"strconv"

	"github.com/luminyra/fp"
)

// checkPort is an ordinary Go function that knows nothing about fp.
func checkPort(n int) (int, error) {
	if n < 1 || n > 65535 {
		return 0, fmt.Errorf("port %d out of range", n)
	}
	return n, nil
}

// parsePort parses an integer, then checks its range; when a step fails, the
// following steps are skipped. AndThen takes a (value, error) function as is.
func parsePort(s string) fp.Result[int] {
	return fp.ResultOf(strconv.Atoi(s)).AndThen(checkPort)
}


func main() {
	for _, s := range []string{"8080", "http", "70000"} {
		fmt.Printf("%-6s -> %v\n", s, parsePort(s))
	}

	// Recover runs only on failure and can supply a fallback; MapErr adds
	// context to the error.
	port := parsePort("http").Recover(func(error) (int, error) { return 8080, nil })
	fmt.Println("fallback port:", port.MustGet())

	_, err := parsePort("70000").MapErr(func(err error) error {
		return fmt.Errorf("read PORT: %w", err)
	}).Get()
	fmt.Println("error:", err)

	// Map is a generic method, so a Result[int] becomes a Result[string]; Get
	// returns to the plain (value, error) form.
	addr, err := parsePort("443").Map(func(n int) string { return ":" + strconv.Itoa(n) }).Get()
	fmt.Println("listen address:", addr, err)
}
View on GitHub

Check the output

ResultOf captures the value and error from integer parsing. If parsing succeeds, Result.AndThen calls the port range check. Use Result.Map to turn the port into a listen address or Result.Or to supply a fallback on failure.

The test example covers a valid port, invalid input, and a port outside the accepted range.

fp/example_test.go
checkPort := func(n int) (int, error) {
	if n < 1 || n > 65535 {
		return 0, fmt.Errorf("port %d out of range", n)
	}
	return n, nil
}

for _, raw := range []string{"8080", "http", "70000"} {
	fmt.Println(fp.ResultOf(strconv.Atoi(raw)).AndThen(checkPort))
}
Expected output
Ok(8080)
Err(strconv.Atoi: parsing "http": invalid syntax)
Err(port 70000 out of range)
View on GitHub

Continue with recovery and conversion.

On this page