반응형
golang Functional Options Pattern
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
}
}
package main
import (
"log"
"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)
}
}
반응형
'Dev > Go' 카테고리의 다른 글
golang 숫자 표시 (0) | 2024.06.13 |
---|---|
golang 문자열 포맷 스트링 tip (0) | 2024.06.13 |
google Project IDX (0) | 2024.04.02 |
golang sqlc query log print (0) | 2024.03.08 |
go 1.22 for loop 변경 (0) | 2024.02.23 |