Skip to content

Instantly share code, notes, and snippets.

@levidurfee
Last active June 30, 2023 16:19
Show Gist options
  • Save levidurfee/9ac2a6f5b51936703ca3ae010a799937 to your computer and use it in GitHub Desktop.
Save levidurfee/9ac2a6f5b51936703ca3ae010a799937 to your computer and use it in GitHub Desktop.
// 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)
}
}
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