其他分享
首页 > 其他分享> > Go代码模板--Option模式

Go代码模板--Option模式

作者:互联网

package main

import (
	"fmt"
	"log"
)

type optsUser struct {
	Addr        string
	ReadTimeout int
	UseSSL      bool
}

type OptionFunc func(opts *optsUser) error

func WithAddr(addr string) OptionFunc {
	return func(opts *optsUser) error {
		opts.Addr = addr
		return nil
	}
}

func WithReadTimeout(timeout int) OptionFunc {
	return func(opts *optsUser) error {
		opts.ReadTimeout = timeout
		return nil
	}
}

func WithUseSSL(ssl bool) OptionFunc {
	return func(opts *optsUser) error {
		opts.UseSSL = ssl
		return nil
	}
}

func NewServer(opts ...OptionFunc) (*optsUser, error) {
	ins := &optsUser{}
	for _, opt := range opts {
		opt(ins)
	}
	return ins, nil
}

func main() {
	ins, err := NewServer(WithAddr(":8080"), WithReadTimeout(1000), WithUseSSL(true))
	if err != nil {
		log.Fatalf("new server error:%v", err)
	}
	fmt.Println(ins.Addr, ins.ReadTimeout, ins.UseSSL)
}

 

标签:return,Option,--,ins,optsUser,func,error,Go,opts
来源: https://www.cnblogs.com/bfstudy/p/16588449.html