调用方标题代码
package main
import (
"demo/cmd/opt/opt"
"fmt"
)
func main() {
client := opt.NewClient("httpServer",
opt.WithProtocol("https"),
opt.WithUrl("www.baidu.com"),
//opt.WithPort(8080),//比如这里可以不用设置端口号,实际就是默认的443
opt.WithTimeout(10),
)
fmt.Printf("client:%+v", client)
//fmt.Printf("%s\n%s\n%s\n%d\n%d\n", client.ServerName, client.Protocol, client.Url, client.Port, client.Timeout)
}
具体实现代码
package opt
type Client struct {
ServerName string
Url string
Timeout int
Port int
Protocol string
}
type OptionsFunc func(*Client)
func NewClient(serverName string, opts ...OptionsFunc) *Client {
client := &Client{
ServerName: "mcp.example.com",
Url: "/mcp/v1/notify",
Timeout: 10,
Port: 443,
Protocol: "https",
}
for _, opt := range opts {
opt(client)
}
return client
}
func WithUrl(url string) OptionsFunc {
return func(client *Client) {
client.Url = url
}
}
func WithTimeout(timeout int) OptionsFunc {
return func(client *Client) {
client.Timeout = timeout
}
}
func WithPort(port int) OptionsFunc {
return func(client *Client) {
client.Port = port
}
}
func WithProtocol(protocol string) OptionsFunc {
return func(client *Client) {
client.Protocol = protocol
}
}
结果
该方法适用入参过多的情况,如果参数过多,可能形参比较长
API server listening at: 127.0.0.1:60990
WARNING: undefined behavior - version of Delve is too old for Go version go1.25rc3 (maximum supported version 1.24)
client:&{ServerName:mcp.example.com Url:www.baidu.com Timeout:10 Port:443 Protocol:https}
调试器 已完成,退出代码为 0