gosms

package module
v0.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 19, 2024 License: Apache-2.0 Imports: 21 Imported by: 1

README

Go SMS

:calling: 一款满足你的多种发送需求的短信发送组件

Go Report Card Go.Dev reference Sourcegraph Release

特点

  1. 支持目前市面多家服务商
  2. 一套写法兼容所有平台
  3. 简单配置即可灵活增减服务商
  4. 内置多种服务商轮询策略、支持自定义轮询策略
  5. 统一的返回值格式,便于日志与监控
  6. 更多等你去发现与改进...

平台支持

目前支持

环境需求

  • Golang >= 1.18

安装

$ go get github.com/pkg6/go-sms

使用

package main

import (
	gosms "github.com/pkg6/go-sms"
	"github.com/pkg6/go-sms/gateways"
	"github.com/pkg6/go-sms/gateways/twilio"
)

func main() {
	sms := gosms.NewParser(gateways.Gateways{Twilio: twilio.Twilio{AccountSID: "ACd********", AuthToken: "***********", TwilioPhoneNumber: "+1********"}})
	// 常规
	sms.Send(18888888888, gosms.MapStringAny{
		"content":  "您的验证码是:****。请不要把验证码泄露给其他人。",
		"template": "SMS_001",
		"data": gosms.MapStrings{
			"code": "6379",
		},
	}, nil)
}

短信内容

由于使用多网关发送,所以一条短信要支持多平台发送,每家的发送方式不一样,但是我们抽象定义了以下公用属性:

  • content 文字内容,使用在像云片类似的以文字内容发送的平台
  • sign_name 签名
  • template 模板 ID,使用在以模板ID来发送短信的平台
  • data 模板变量,使用在以模板ID来发送短信的平台

所以,在使用过程中你可以根据所要使用的平台定义发送的内容。

sms.Send(18888888888, gosms.MapStringAny{
    "content":  "您的验证码是:****。请不要把验证码泄露给其他人。",
    "template": "SMS_001",
    "data": gosms.MapStrings{
        "code": "6379",
    },
}, nil)

你也可以使用闭包来返回对应的值:

sms.Send(18888888888, gosms.MapStringAny{
    "content": func(gateway gosms.IGateway) string {
        return "您的验证码是:****。请不要把验证码泄露给其他人。"
    },
    "template": func(gateway gosms.IGateway) string {
        if gateway.GetName() == "aliyun" {
            return "TP2818"
        }
        return "SMS_001"
    },
    "data": func(gateway gosms.IGateway) gosms.MapStrings {
        return map[string]string{
            "code": "1234",
        }
    },
}, nil)

发送网关

默认使用初始化中的网关发送,如果某一条短信你想要覆盖默认的设置。在 send 方法中使用第三个参数即可:

sms := gosms.NewGateways(twilio.GateWay("ACd********", "***********", "+1***********"))
sms.Send(18888888888, gosms.MapStringAny{
    "content": "您的验证码是:****。请不要把验证码泄露给其他人。",
}, nil)

自定义网关

本拓展已经支持用户自定义网关,你可以很方便的配置即可当成与其它拓展一样的使用:

sms := gosms.NewGateways()
sms.Extend("aliyun", aliyun.GateWay("accessKeyId", "accessKeySecret"))
sms.Send(18888888888, gosms.MapStringAny{
    "content": "您的验证码是:****。请不要把验证码泄露给其他人。",
}, []string{"aliyun"})

自定义网关实现接口

// IGateway 网关
type IGateway interface {
	// I 用于初始化默认值
	I() IGateway
	// GetName 网关名称
	GetName() string
	// Send 发送操作
	Send(to IPhoneNumber, message IMessage) (SMSResult, error)
}

通过Sender函数去发送

package main

import (
	"fmt"
	gosms "github.com/pkg6/go-sms"
	"github.com/pkg6/go-sms/gateways/twilio"
)

func main() {
	gateway := twilio.GateWay("ACd********", "********", "+1111111")
	var message = gosms.MessageContent("Hello from Twilio")
	number := gosms.CHNPhoneNumber(18888888888)
	result, err := gosms.Sender(number, message, gateway)
	if resp, ok := result.ClientResult.Response.(twilio.Response); ok {
		fmt.Println(resp)
	}
	fmt.Println(err)
}

加入我们

如果你认可我们的开源项目,有兴趣为 go-sms的发展做贡献,竭诚欢迎加入我们一起开发完善。无论是报告错误或是 Pull Request 开发,那怕是修改一个错别字也是对我们莫大的帮助。

Documentation

Index

Constants

View Source
const StatusFailure = "failure"
View Source
const StatusSuccess = "success"

Variables

Functions

func Base64Encode

func Base64Encode(text string) string

Base64Encode base64

func GatewayName

func GatewayName(gateway IGateway) string

GatewayName 获取Gateway name 如果不为空就是包的名字

func GetPhoneNumber

func GetPhoneNumber(number IPhoneNumber) string

GetPhoneNumber 获取手机号码

func IsZero

func IsZero(s any) bool

IsZero 判断Struct是否被初始化

func Md5String

func Md5String(text string) string

Md5String md5加密

func Rand

func Rand(min, max int) int

Rand 随时数

func RandLetterString

func RandLetterString(lenNum int) string

RandLetterString 生成随机字母

func RandNumString

func RandNumString(lenNum int) string

RandNumString 生成随机数字

func RandString

func RandString(lenNum int) string

RandString 生成随机字符串

func RandomBytes

func RandomBytes(length int) ([]byte, error)

RandomBytes random_bytes()

func RandomInt

func RandomInt(min, max int) (int, error)

RandomInt random_int()

func ReplaceMapStrings

func ReplaceMapStrings(s string, repl MapStrings) string

ReplaceMapStrings 您手机注册的验证码为:【变量1】,如有问题请拨打客服电话:【变量2】 new = MapStrings{"变量1":"111","变量2"::"222"} 您手机注册的验证码为:111,如有问题请拨打客服电话:222

func ReplaceMapStringsForStringIndex

func ReplaceMapStringsForStringIndex(s, old string, news MapStrings) string

ReplaceMapStringsForStringIndex 您手机注册的验证码为:"您手机注册的验证码为:【变量】,如有问题请拨打客服电话:【变量】" new = MapStrings{"0": "111", "1": "222"} 您手机注册的验证码为:【111】,如有问题请拨打客服电话:【222】

func Sha1String

func Sha1String(text string) string

Sha1String sha1加密

func Sha256String

func Sha256String(text string) string

func Sleep

func Sleep(t int64)

Sleep sleep()

func Time

func Time() int64

Time time()

func TimeString

func TimeString() string

TimeString Time time()

func URLEncode

func URLEncode(text string) string

URLEncode urlencode()

func Uniqid

func Uniqid(prefix string) string

Uniqid 基于以微秒计的当前时间,生成一个唯一的ID

func Usleep

func Usleep(t int64)

Usleep usleep()

Types

type ClientResult

type ClientResult struct {
	// 状态值
	Status string `json:"status" xml:"status"`
	// 请求返回的数据
	Response any `json:"response" xml:"response"`
	// 错误返回的异常
	Exception error `json:"exception" xml:"exception"`
}

ClientResult 网关响应结果的结构体

type GatewayMap

type GatewayMap map[string]IGateway

type GoSMS

type GoSMS struct {

	//发送网关的别名
	SendAsNames []string
	// contains filtered or unexported fields
}
var (
	SingletonGoSMS *GoSMS
)

func GoSMSInstance

func GoSMSInstance(gosms GoSMS) *GoSMS

GoSMSInstance 单例模式

func NewGateways

func NewGateways(gateways ...IGateway) *GoSMS

NewGateways 携带网关实例

func NewParser

func NewParser(parser IParser) *GoSMS

NewParser 携带解析器实例

func (*GoSMS) AddSendGateway

func (sms *GoSMS) AddSendGateway(gateway IGateway) *GoSMS

AddSendGateway 直接注册发送网关

func (GoSMS) Clone

func (sms GoSMS) Clone() *GoSMS

func (*GoSMS) Extend

func (sms *GoSMS) Extend(name string, gateway IGateway) *GoSMS

Extend 注册网关

func (*GoSMS) Send

func (sms *GoSMS) Send(to, message any, sendAsNames any) (smsResults SMSResults, err error)

Send 批量发送

type HashMap

type HashMap struct {
	HashMap sync.Map
}

HashMap hashmao

func (*HashMap) Delete

func (g *HashMap) Delete(key string)

Delete 删除

func (*HashMap) Get

func (g *HashMap) Get(key string) (any, bool)

Get 获取

func (*HashMap) Keys

func (g *HashMap) Keys() []string

Keys 键值

func (*HashMap) Set

func (g *HashMap) Set(key string, value any)

Set 设置

func (*HashMap) ToMaps

func (g *HashMap) ToMaps() map[string]any

ToMaps 转maps

func (*HashMap) Values

func (g *HashMap) Values() []any

Values value值

type IGateway

type IGateway interface {
	// I 用于初始化默认值
	I() IGateway
	// AsName 网关名称
	AsName() string
	// Send 发送操作
	Send(to IPhoneNumber, message IMessage) (SMSResult, error)
}

IGateway 网关

type IMessage

type IMessage interface {
	I() IMessage
	// GetMessageType 消息类型
	GetMessageType() int
	// GetSignName 签名
	GetSignName(gateway IGateway) string
	// GetContent 文字内容,使用在像云片类似的以文字内容发送的平台
	GetContent(gateway IGateway) string
	// GetTemplate 模板 ID,使用在以模板ID来发送短信的平台
	GetTemplate(gateway IGateway) string
	// GetData 模板变量,使用在以模板ID来发送短信的平台
	GetData(gateway IGateway) MapStrings
	// GetGateways 消息指定渠道发送
	GetGateways() []IGateway
}

IMessage 消息内容

func MessageContent

func MessageContent(content string) IMessage

func MessageTemplate

func MessageTemplate(template string, data MapStrings) IMessage

type IParser

type IParser interface {
	// FormatGateways 根据配置可以获取到对应到注册网关
	FormatGateways() (gateways []IGateway)
}

IParser 配置信息解析器

type IPhoneNumber

type IPhoneNumber interface {
	I() IPhoneNumber
	// GetCode 手机号号码前缀 例:中国 86
	GetCode() int
	// GetNumber 手机号 18888888888
	GetNumber() int
	// GetUniversalNumber 返回 +8618888888888
	GetUniversalNumber() string
	// GetZeroPrefixedNumber 返回 008618888888888
	GetZeroPrefixedNumber() string
}

IPhoneNumber 手机号

func CHNPhoneNumber

func CHNPhoneNumber(number int) IPhoneNumber

CHNPhoneNumber 中国手机号

func NoCodePhoneNumber

func NoCodePhoneNumber(number int) IPhoneNumber

NoCodePhoneNumber 无code手机号

type Lock

type Lock struct {
	L *sync.Mutex
}

func (*Lock) LockInit

func (l *Lock) LockInit()

type MapStringAny

type MapStringAny map[string]any

MapStringAny 二维以上map

func (MapStringAny) Exist

func (maps MapStringAny) Exist(k string) bool

Exist 键值是否存在

func (MapStringAny) Get

func (maps MapStringAny) Get(k string, dv any) any

Get 获取value 要设置默认值

func (MapStringAny) JsonUnmarshal

func (maps MapStringAny) JsonUnmarshal(v any) error

JsonUnmarshal 解析json到实体上

func (MapStringAny) Set

func (maps MapStringAny) Set(k string, v any)

Set 添加值 force=true 覆盖原值

func (MapStringAny) SetForce

func (maps MapStringAny) SetForce(k string, v any, force bool)

SetForce Set 添加值 force=true 覆盖原值

func (MapStringAny) ToIMessage

func (maps MapStringAny) ToIMessage() IMessage

ToIMessage 获取value 要设置默认值

func (MapStringAny) ToJson

func (maps MapStringAny) ToJson() (string, error)

ToJson 转json 字节流

func (MapStringAny) Verify

func (maps MapStringAny) Verify(mustKey []string) MapStrings

Verify 验证出参数

type MapStrings

type MapStrings map[string]string

MapStrings 一纬map

func MergeMapsString

func MergeMapsString(maps ...MapStrings) MapStrings

MergeMapsString 多个map合并

func (MapStrings) Delete

func (maps MapStrings) Delete(k string)

Delete 删除指定到key值

func (MapStrings) Exist

func (maps MapStrings) Exist(k string) bool

Exist 键值是否存在

func (MapStrings) GetDefault

func (maps MapStrings) GetDefault(k, d string) string

GetDefault 获取值并携带默认值

func (MapStrings) Implode

func (maps MapStrings) Implode(sep string) string

Implode values 转字符串

func (MapStrings) Keys

func (maps MapStrings) Keys() []string

Keys keys

func (MapStrings) Set

func (maps MapStrings) Set(k, v string)

Set 添加值 force=true 覆盖原值

func (MapStrings) SetForce

func (maps MapStrings) SetForce(k, v string, force bool)

SetForce Set 添加值 force=true 覆盖原值

func (MapStrings) ToJson

func (maps MapStrings) ToJson() (string, error)

ToJson 转json字符串

func (MapStrings) ToUrlQuery

func (maps MapStrings) ToUrlQuery(kSort bool) string

ToUrlQuery 转url请求参数

func (MapStrings) Values

func (maps MapStrings) Values() []string

Values values

func (MapStrings) Verify

func (maps MapStrings) Verify(mustKey []string) MapStrings

Verify 验证出参数

type Message

type Message struct {
	//消息类型
	Type int `json:"type"`
	//签名
	SignName any `json:"sign_name"`
	//消息内容
	Content any `json:"content"`
	//消息模版
	Template any `json:"template"`
	//消息模版数据
	Data any `json:"data"`
	//网关
	Gateways []IGateway `json:"gateways"`
}

func (*Message) GetContent

func (m *Message) GetContent(gateway IGateway) string

func (*Message) GetData

func (m *Message) GetData(gateway IGateway) MapStrings

func (*Message) GetGateways

func (m *Message) GetGateways() []IGateway

func (*Message) GetMessageType

func (m *Message) GetMessageType() int

func (*Message) GetSignName

func (m *Message) GetSignName(gateway IGateway) string

func (*Message) GetTemplate

func (m *Message) GetTemplate(gateway IGateway) string

func (Message) I

func (m Message) I() IMessage

type MessageContentFun

type MessageContentFun func(gateway IGateway) string

MessageContentFun 生成消息内容闭包

type MessageDataFun

type MessageDataFun func(gateway IGateway) MapStrings

MessageDataFun 生成消息模版数据闭包

type MessageSignNameFun

type MessageSignNameFun func(gateway IGateway) string

MessageSignNameFun 生成签名闭包

type MessageTemplateFun

type MessageTemplateFun func(gateway IGateway) string

MessageTemplateFun 生成消息模版闭包

type PhoneNumber

type PhoneNumber struct {
	Number int `json:"number"`
	Code   int `json:"code"`
}

func (*PhoneNumber) GetCode

func (p *PhoneNumber) GetCode() int

func (*PhoneNumber) GetNumber

func (p *PhoneNumber) GetNumber() int

func (*PhoneNumber) GetUniversalNumber

func (p *PhoneNumber) GetUniversalNumber() string

func (*PhoneNumber) GetZeroPrefixedNumber

func (p *PhoneNumber) GetZeroPrefixedNumber() string

func (PhoneNumber) I

func (p PhoneNumber) I() IPhoneNumber

type SMSResult

type SMSResult struct {
	Gateway      IGateway     `json:"gateway"`
	PhoneNumber  IPhoneNumber `json:"phone_number"`
	Message      IMessage     `json:"message"`
	ClientResult ClientResult `json:"client_result"`
}

SMSResult 网关统一的结构体

func BuildSMSResult

func BuildSMSResult(phoneNumber IPhoneNumber, message IMessage, gateway IGateway, response any) SMSResult

BuildSMSResult 在网关快速生成结构体

func Sender

func Sender(number IPhoneNumber, message IMessage, gateway IGateway) (SMSResult, error)

Sender 通过interface 发送

type SMSResults

type SMSResults []SMSResult

SMSResults 批量发

func SenderGateways

func SenderGateways(number IPhoneNumber, message IMessage, gateways []IGateway) (smsResult SMSResults, err error)

SenderGateways 多渠道发送短信

func SenderNumbers

func SenderNumbers(numbers []IPhoneNumber, message IMessage, gateway IGateway) (smsResult SMSResults, err error)

SenderNumbers 多手机号发送短信

Directories

Path Synopsis
_example
gosms command
sender/ihuiyi command
sender/juhe command
sender/lmobile command
sender/smsbao command
sender/twilio command
sender/yunxin command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL