快速上手
把端口解析与范围校验串成一条 Result 链。
运行端口示例
使用 Go 1.27 或更高版本。在项目模块中安装 fp 后,把下方完整示例复制到 main.go,运行 go run .。也可在 fp 源码目录运行 go run ./examples/result。
go get github.com/luminyra/fp// 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)
}检查输出
ResultOf 接住整数解析的值和错误。成功时,Result.AndThen 调用端口范围检查。随后可用 Result.Map 把端口转成监听地址,或用 Result.Or 为失败提供默认值。
下方测试示例覆盖合法端口、非法输入和超出范围三种情况。
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))
}Ok(8080)
Err(strconv.Atoi: parsing "http": invalid syntax)
Err(port 70000 out of range)接着阅读 Result 的恢复和转换。