Skip to content

Instantly share code, notes, and snippets.

@nicewook
Last active February 11, 2024 04:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicewook/c3fe5c76d02946d0d0c60dbd09bddf46 to your computer and use it in GitHub Desktop.
Save nicewook/c3fe5c76d02946d0d0c60dbd09bddf46 to your computer and use it in GitHub Desktop.
함수형 옵션 패턴
package main
import (
"fmt"
)
// Server - 서버 설정을 위한 구조체
type Server struct {
Host string
Port int
UseTLS bool
}
// ServerOption - 서버 설정 옵션을 위한 함수 타입
type ServerOption func(*Server)
// NewServer - 서버 생성자 함수와 함께 선택적 옵션을 적용
func NewServer(options ...ServerOption) *Server {
// 기본값 설정
server := &Server{
Host: "localhost",
Port: 8080,
UseTLS: false,
}
// 각 옵션 적용
for _, option := range options {
option(server)
}
return server
}
// WithHost - 호스트 설정 옵션
func WithHost(host string) ServerOption {
return func(s *Server) {
s.Host = host
}
}
// WithPort - 포트 설정 옵션
func WithPort(port int) ServerOption {
return func(s *Server) {
s.Port = port
}
}
// UseTLS - TLS 사용 설정 옵션
func UseTLS(useTLS bool) ServerOption {
return func(s *Server) {
s.UseTLS = useTLS
}
}
func main() {
// 기본 서버 생성
server := NewServer()
fmt.Println(server)
// 옵션을 사용하여 서버 생성
customServer := NewServer(WithHost("example.com"), WithPort(443), UseTLS(true))
fmt.Println(customServer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment