当前位置:网站首页>Go use options mode to set parameters
Go use options mode to set parameters
2022-04-22 02:26:00 【keenw】
Functional Options Pattern( Functional option mode ) It can be used to pass different options and configurations into the method . Every time the option parameters are changed , You can not change the parameters of the method or interface , This ensures interface compatibility . Use Options The mode of is also more conducive to the expansion of the program , So it has been widely used in many packages .
Let me explain in detail Options How to use :
1. Use functions to pass parameters
Generally, we need to create a service client , It may be written like this
type Client struct {
url string
username string
password string
}
func NewClient(url string, username string, password string,db string) *Client {
return &Client{
url: url,
username: username,
password: password
}
}
When you write this , Parameters are passed through New Method to pass in . Later, because of demand , You also need to add the following optional parameters
readTimeout time.Duration // Read timeout
charset string // Coding can be configured
If passed by parameter , We have to modify New Parameter of method , If multiple projects depend on this package , Then the references have to be modified accordingly New Method parameter . So how to solve this problem well , This is the time Options The model appears .
2. Use options Option mode
We first use the above optional parameters as options How to define ( here options Lowercase , The specific configuration items are not exposed to the outside world )
type options struct {
readTimeout time.Duration
charset string
}
Then we define Option Structure
type Option func(*options)
Then we define the configuration options Public method of parameters in , Used to set parameters
func WithReadTimeout(timeout time.Duration) Option {
return func(o *options) {
o.readTimeout = timeout
}
}
func WithCharset(charset string) Option {
return func(o *options) {
o.charset = charset
}
}
At the same time options Add to Client in , And in New Method
type Client struct {
url string
username string
password string
opts options
}
func NewClient(url string, username string, password string,opts ...Option) *Client {
// Create a default options
op := options{
readTimeout: 10,
charset: "utf8",
}
// Call the parameters passed in dynamically to set the value
for _, option := range opts {
option(&op)
}
return &Client{
url: url,
username: username,
password: password,
opts: op,
}
}
Use Options After the mode of , If you add parameters, you don't need to modify them New The method . We only need to add parameters in options Add the corresponding attribute to , At the same time, configure corresponding external WithXXX The method can .
So we can call it in the following way
client := NewClient("localhost:3333","test","test",WithReadTimeout(100),WithCharset("gbk"))
The following optional parameters can be passed in any number of Option 了 . It's configured here Option After more parameters , The configuration is too long , We further encapsulate it into a function
func Options() []Option{
return []{
WithReadTimeout(100),
WithCharset("gbk")
}
}
client := NewClient("localhost:3333","test","test",Options()...)
Come here options The option model can easily transfer optional parameters , At the same time, you don't need to add a parameter to add the parameter of the method .
3. Let's take a look at some other options Users of
3.1. gRPC It is also widely used in options Pass parameters in option mode
Here is Dial Methods use options Option mode
type dialOptions struct {
unaryInt UnaryClientInterceptor
streamInt StreamClientInterceptor
chainUnaryInts []UnaryClientInterceptor
chainStreamInts []StreamClientInterceptor
cp Compressor
dc Decompressor
bs internalbackoff.Strategy
block bool
returnLastError bool
timeout time.Duration
scChan <-chan ServiceConfig
authority string
copts transport.ConnectOptions
callOptions []CallOption
balancerBuilder balancer.Builder
channelzParentID int64
disableServiceConfig bool
disableRetry bool
disableHealthCheck bool
healthCheckFunc internal.HealthChecker
minConnectTimeout func() time.Duration
defaultServiceConfig *ServiceConfig // defaultServiceConfig is parsed from defaultServiceConfigRawJSON.
defaultServiceConfigRawJSON *string
resolvers []resolver.Builder
}
// options The processing is handed over to the implementation interface class
type DialOption interface {
apply(*dialOptions)
}
func Dial(target string, opts ...DialOption) (*ClientConn, error) {
return DialContext(context.Background(), target, opts...)
}
---------- Concrete realization apply The implementation of the ----------------
type funcDialOption struct {
f func(*dialOptions)
}
func (fdo *funcDialOption) apply(do *dialOptions) {
fdo.f(do)
}
func WithTimeout(d time.Duration) DialOption {
return newFuncDialOption(func(o *dialOptions) {
o.timeout = d
})
}
I can see it above grpc Of dial The method is another implementation options The way , meanwhile dialOptions It also encapsulates other options, The more interesting one is callOptions, It's a CallOption Type array , and CallOption It's a interface The type of , as follows :
type CallOption interface {
before(*callInfo) error
after(*callInfo, *csAttempt)
}
This is a bit like AOP Same , by call Pre and post callbacks are provided before and after the call .
3.2 There are many other frameworks that are also widely used options Pattern
1. bilibili Open source framework kratos: https://github.com/go-kratos/kratos/blob/main/options.go
2. beego Frame encapsulated httpclient: beego/httpclient.go at develop · beego/beego · GitHub
3. etc...
版权声明
本文为[keenw]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220224492224.html
边栏推荐
- 《k3s 源码解析2 ----master逻辑源码分析》
- Why is Nacos so strong
- Oracle table Association divergence
- Why can the Internet industry attract more and more young people? Especially programmers
- Pychar executes multiple script files at the same time
- K3s source code analysis 2 - Master Logic source code analysis
- MySQL cannot find my INI file
- 3D立体相册模板(大小可更改)
- Knowledge points of machine learning and deep learning
- 我靠,有人在我的代码注释里的“下毒”?
猜你喜欢

In PostgreSQL, convert a string to an integer or floating-point type in the query result

Explain the mathematical process of neural network like a pile of LEGO

Evaluation of arithmetic four mixed operation expression

Page 78 digital twin + smart building solutions

编程主要学什么

AI应用说-智慧农场(牛场无人监控)

Page 58 Siemens digital solutions for machine tool industry

2022年物联网安全的发展趋势
![[论文阅读] Active Class Incremental Learning for Imbalanced Datasets](/img/20/ecfffcdeed6813a6bdb703794a2607.png)
[论文阅读] Active Class Incremental Learning for Imbalanced Datasets

2022年软件设计师考试知识点:线性表
随机推荐
14. System information viewing
102 page master plan for new generation digital transformation and informatization
风控产品定额的陷阱都有哪些?
黑夜也能五颜六色,用深度学习实现全彩夜视系统
SSLHandshakeException
Another way to write the fluent interface is to write a part first, then material, and put the method body in the method body
AI application theory - Smart farm (cattle farm without monitoring)
When people get closer to the industrial Internet, they can see it more and more clearly
Swoole high performance in memory database use and configuration tutorial
Page 49 information planning and digital transformation of petroleum and petrochemical industry
Knowledge points of machine learning and deep learning
算数四则混合运算表达式求值
【项目】小帽外卖(七)
JMeter + Jenkins + ant persistence
[pytorch image classification] alexnet network structure
Flutter跳转界面
User interaction, formatted output, basic operators
Nacos 为什么这么强
Introduction to Alibaba's super large-scale Flink cluster operation and maintenance system
Login procedure 2