-
-
Save levidurfee/9ac2a6f5b51936703ca3ae010a799937 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://golang.cafe/blog/golang-functional-options-pattern.html | |
package main | |
import ( | |
"log" | |
"time" | |
"github.com/acme/pkg/server" | |
) | |
func main() { | |
svr := server.New( | |
server.WithHost("localhost"), | |
server.WithPort(8080), | |
server.WithTimeout(time.Minute), | |
server.WithMaxConn(120), | |
) | |
if err := svr.Start(); err != nil { | |
log.Fatal(err) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package server | |
type Server { | |
host string | |
port int | |
timeout time.Duration | |
maxConn int | |
} | |
func New(options...func( * Server)) * Server { | |
svr: = & Server {} | |
for _, | |
o: = range options { | |
o(svr) | |
} | |
return svr | |
} | |
func(s * Server) Start() error { | |
// todo | |
} | |
func WithHost(host string) func( * Server) { | |
return func(s * Server) { | |
s.host = host | |
} | |
} | |
func WithPort(port int) func( * Server) { | |
return func(s * Server) { | |
s.port = port | |
} | |
} | |
func WithTimeout(timeout time.Duration) func( * Server) { | |
return func(s * Server) { | |
s.timeout = timeout | |
} | |
} | |
func WithMaxConn(maxConn int) func( * Server) { | |
return func(s * Server) { | |
s.maxConn = maxConn | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment