hincky的主页 hincky的主页
  • 学习笔记

    • Vue笔记
    • Vuepress
    • nginx
  • 语言类

    • java
    • go
    • python
    • 设计模式
  • 框架类

    • Spring
    • Spring Security
    • Mybatis
  • 容器技术

    • docker
    • k8s
    • helm
    • prometheus
    • grafana
    • jenkins
  • 命令集合

    • linux命令
    • docker命令
    • git命令
    • vim命令
    • k8s命令
  • 数据库

    • sql
    • mysql
  • 协议

    • 网络模型
    • http/1.1
    • WebSocket
    • http/2
    • TLS/SSL
    • tcp
    • IP
    • tcpdump抓包命令
    • wireshark抓包工具
  • 通用

    • Git
  • 技术分享

    • git push/pull总是超时怎么办
    • idea debug技巧
    • postman使用
    • 问题总结
    • idea使用技巧
  • Oauth2

    • Oauth2原理
  • 项目列表

    • redis项目
    • 微服务项目
  • 分类
  • 标签
  • 归档
  • 随笔
GitHub (opens new window)

Hincky

当有趣的人,做想做的事
  • 学习笔记

    • Vue笔记
    • Vuepress
    • nginx
  • 语言类

    • java
    • go
    • python
    • 设计模式
  • 框架类

    • Spring
    • Spring Security
    • Mybatis
  • 容器技术

    • docker
    • k8s
    • helm
    • prometheus
    • grafana
    • jenkins
  • 命令集合

    • linux命令
    • docker命令
    • git命令
    • vim命令
    • k8s命令
  • 数据库

    • sql
    • mysql
  • 协议

    • 网络模型
    • http/1.1
    • WebSocket
    • http/2
    • TLS/SSL
    • tcp
    • IP
    • tcpdump抓包命令
    • wireshark抓包工具
  • 通用

    • Git
  • 技术分享

    • git push/pull总是超时怎么办
    • idea debug技巧
    • postman使用
    • 问题总结
    • idea使用技巧
  • Oauth2

    • Oauth2原理
  • 项目列表

    • redis项目
    • 微服务项目
  • 分类
  • 标签
  • 归档
  • 随笔
GitHub (opens new window)
  • java

  • python

  • Spring

  • SpringMVC

  • SpringSecurity

  • Mybatis

  • 设计模式

  • Go

    • 基础语法

      • 环境安装
        • 你好,Go语言
        • 环境安装
        • 目录结构
        • 命令
        • 开发工具
        • 学习网址
      • 变量声明
        • 概述
        • 数据类型
          • 字符串
          • 布尔
          • 数字
        • 常量声明
        • 变量声明
        • 输出方法
      • 数组
        • 概述
        • 声明数组
        • 注意事项
      • Slice 切片
        • 概述
        • 声明切片
        • 截取切片
        • 追加切片
        • 删除切片
      • Struct 结构体
        • 概述
        • 声明结构体
        • 生成 JSON
        • 改变数据
      • Map 集合
        • 概述
        • 声明 Map
        • 生成 JSON
        • 编辑和删除
      • 循环
        • 概述
        • 循环 array
        • 循环 slice
        • 循环 map
        • break
        • continue
        • goto
        • switch
      • 函数
        • 概述
        • 函数定义
        • 值传递
        • 引用传递
        • MD5
        • 获取当前时间字符串
        • 获取当前时间戳
        • 生成签名
      • chan 通道
        • 概述
        • 声明 chan
        • 写入 chan
        • 读取 chan
        • 关闭 chan
        • 示例
      • defer 函数
        • 概述
        • 执行顺序
        • 闭包
        • Return
          • 一
          • 二
          • 三
          • 四
        • os.Exit
        • 不同协程
        • 答案解析
        • go-gin-api 系列文章
      • 解析 JSON 数据
        • 概述
        • JSON 结构
        • go-gin-api 系列文章
      • Unmarshal 遇到的小坑
        • 1.问题现象描述
        • 2.问题影响描述
        • 3.引起问题的原因
        • 4.问题的解决方案
      • 结构(struct) 实现 接口(interface)
        • 代码示例
        • 代码解释
          • 一、
          • 二、
          • 三、
      • Dial(target string, opts …DialOption) 的写法
        • 一
        • 二
        • 场景
        • 代码实现
        • 输出
      • RFC3339 时间格式化
        • 运行一下
        • 小结
      • 常用签名算法的基准测试
        • MD5 单向散列加密
        • AES 对称加密
        • RSA 非对称加密
        • 最后
      • 分享两个在开发中需注意的小点
        • 不要使用 + 和 fmt.Sprintf 操作字符串
          • +
          • fmt.Sprintf
          • bytes.NewBufferString
        • 对于固定字段的键值对,不要使用 map[string]interface{}
          • map[string]interface{}
          • 临时 Struct
        • 小结
          • 推荐阅读
      • Pool 来减少 GC 压力
        • 前言
        • sync.Pool
        • 小结
        • 推荐阅读
      • 基于逃逸分析来提升程序性能
        • 前言
        • 什么是逃逸分析?
        • 如何确定是否逃逸?
        • 可能出现逃逸的场景
          • 01
          • 02
          • 03
        • 小结
        • 推荐阅读
      • Map 来解决 map 的并发操作问题
        • 前言
        • map 并发操作出现问题
        • sync.Map 解决并发操作问题
        • 计算 map 长度
        • 计算 sync.Map 长度
        • 小结
        • 推荐阅读
      • WaitGroup 来实现并发操作
        • 前言
        • sync.WaitGroup 正确使用
        • sync.WaitGroup 闭坑指南
          • 01
          • 02
          • 03
        • 小结
        • 推荐阅读
    • Gin框架

    • Go gRPC

    • go-gin-api [文档]

    • go基本介绍
      • 安装go
      • hello world
      • 变量类型
      • 变量和声明
        • 定义和赋值分开
        • 定义和赋值合并
        • 最简单的写法
        • 最简写法结合函数
        • 多个变量同时赋值
        • 变量总结
      • if
      • 导入包
      • 运行go代码
      • 函数声明
        • 返回值个数
        • 参数接收
        • 两个参数都接收
        • 只接收其中一个参数
    • Go结构体
      • 定义结构体
      • 声明和初始化
        • 结构体字段
        • 结构体初始化
        • 函数参数传递方式
        • 镜像复制
        • 指针
      • 结构体上的函数
      • 构造器
        • new
    • Go相关项目推荐
      • 收录golang的一些好的开源项目
  • 后端
  • Go
  • 基础语法
hincky
2022-11-21
目录

Dial(target string, opts …DialOption) 的写法

咱们平时是这样使用 grpc.Dial 方法的,比如:

conn, err := grpc.Dial("127.0.0.1:8000",
		grpc.WithChainStreamInterceptor(),
		grpc.WithInsecure(),
		grpc.WithBlock(),
		grpc.WithDisableRetry(),
	)
1
2
3
4
5
6

咱们怎么能写出类似这样的调用方式,它是怎么实现的?

这篇文章咱们写一个 Demo,其实很简单,一步步往下看。

# 一

opts …DialOption,这个是不定参数传递,参数的类型为 DialOption,不定参数是指函数传入的参数个数为不定数量,可以不传,也可以为多个。

写一个不定参数传递的方法也很简单,看看下面这个方法 1 + 2 + 3 = 6。

func Add(a int, args ...int) (result int) {
	result += a
	for _, arg := range args {
		result += arg
	}
	return
}

fmt.Println(Add(1, 2, 3))

// 输出 6
1
2
3
4
5
6
7
8
9
10
11

其实平时我们用的 fmt.Println()、fmt.Sprintf() 都属于不定参数的传递。

# 二

WithInsecure()、WithBlock() 类似于这样的 With 方法,其实作用就是修改 dialOptions 结构体的配置,之所以这样写我个人认为是面向对象的思想,当配置项调整的时候调用方无需修改。

# 场景

咱们模拟一个场景,使用 不定参数 和 WithXXX 这样的写法,写个 Demo,比如我们要做一个从附近找朋友的功能,配置项有:性别、年龄、身高、体重、爱好,我们要找性别为女性,年龄为30岁,身高为160cm,体重为55kg,爱好为爬山的人,希望是这样的调用方式:

friends, err := friend.Find("附近的人",
		friend.WithSex(1),
		friend.WithAge(30),
		friend.WithHeight(160),
		friend.WithWeight(55),
		friend.WithHobby("爬山"))
1
2
3
4
5
6

# 代码实现

// option.go

package friend

import (
	"sync"
)

var (
	cache = &sync.Pool{
		New: func() interface{} {
			return &option{sex: 0}
		},
	}
)

type Option func(*option)

type option struct {
	sex    int
	age    int
	height int
	weight int
	hobby  string
}

func (o *option) reset() {
	o.sex = 0
	o.age = 0
	o.height = 0
	o.weight = 0
	o.hobby = ""
}

func getOption() *option {
	return cache.Get().(*option)
}

func releaseOption(opt *option) {
	opt.reset()
	cache.Put(opt)
}

// WithSex setup sex, 1=female 2=male
func WithSex(sex int) Option {
	return func(opt *option) {
		opt.sex = sex
	}
}

// WithAge setup age
func WithAge(age int) Option {
	return func(opt *option) {
		opt.age = age
	}
}

// WithHeight set up height
func WithHeight(height int) Option {
	return func(opt *option) {
		opt.height = height
	}
}

// WithWeight set up weight
func WithWeight(weight int) Option {
	return func(opt *option) {
		opt.weight = weight
	}
}

// WithHobby set up Hobby
func WithHobby(hobby string) Option {
	return func(opt *option) {
		opt.hobby = hobby
	}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// friend.go

package friend

import (
	"fmt"
)

func Find(where string, options ...Option) (string, error) {
	friend := fmt.Sprintf("从 %s 找朋友\n", where)

	opt := getOption()
	defer func() {
		releaseOption(opt)
	}()

	for _, f := range options {
		f(opt)
	}

	if opt.sex == 1 {
		sex := "性别:女性"
		friend += fmt.Sprintf("%s\n", sex)
	}
	if opt.sex == 2 {
		sex := "性别:男性"
		friend += fmt.Sprintf("%s\n", sex)
	}

	if opt.age != 0 {
		age := fmt.Sprintf("年龄:%d岁", opt.age)
		friend += fmt.Sprintf("%s\n", age)
	}

	if opt.height != 0 {
		height := fmt.Sprintf("身高:%dcm", opt.height)
		friend += fmt.Sprintf("%s\n", height)
	}

	if opt.weight != 0 {
		weight := fmt.Sprintf("体重:%dkg", opt.weight)
		friend += fmt.Sprintf("%s\n", weight)
	}

	if opt.hobby != "" {
		hobby := fmt.Sprintf("爱好:%s", opt.hobby)
		friend += fmt.Sprintf("%s\n", hobby)
	}

	return friend, nil
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// main.go

package main

import (
	"demo/friend"
	"fmt"
)

func main() {
	friends, err := friend.Find("附近的人",
		friend.WithSex(1),
		friend.WithAge(30),
		friend.WithHeight(160),
		friend.WithWeight(55),
		friend.WithHobby("爬山"))

	if err != nil {
		fmt.Println(err)
	}

	fmt.Println(friends)
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

# 输出

从 附近的人 找朋友
性别:女性
年龄:30岁
身高:160cm
体重:55kg
爱好:爬山
1
2
3
4
5
6
编辑 (opens new window)
结构(struct) 实现 接口(interface)
RFC3339 时间格式化

← 结构(struct) 实现 接口(interface) RFC3339 时间格式化→

最近更新
01
人生前期重要的能力
05-17
02
防火墙命令
04-11
03
docker-compose部署mysql主从集群
03-22
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Hincky | MIT License | 粤ICP备2022120427号
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式