Build a Go‑Based SMS Verification Login with Gin and Viper
This guide walks through creating a phone‑number SMS verification login system in Go using Gin, Viper, and Tencent Cloud SMS, covering service registration, configuration loading, client implementation with functional options, code generation, sending, and Redis‑based verification.
Most modern apps use phone number verification via SMS codes. This guide shows how to implement SMS verification login in Go using the Gin framework and Tencent Cloud SMS service.
First, obtain a Tencent Cloud SMS account, create a signature and template (free trial offers 100 messages).
Configure the SMS settings in a YAML file and load them with Viper:
sms:
secret-key: # secret key from console
secret-id: # secret id from console
sms-sdk-app-id: # application id
Sign-name: # signature
template-id: # template idDefine configuration structs and load them into the global options:
// sms sending options
type SmsOptions struct {
SecretKey string `json:"secret-key,omitempty" mapstructure:"secret-key"`
SecretId string `json:"secret-id,omitempty" mapstructure:"secret-id"`
SmsSdkAppId string `json:"sms-sdk-app-id,omitempty" mapstructure:"sms-sdk-app-id"`
SignName string `json:"sign-name,omitempty" mapstructure:"sign-name"`
TemplateId string `json:"template-id,omitempty" mapstructure:"template-id"`
}
...
func NewOptions() *Options {
o := Options{
GenericServerRunOptions: genericoptions.NewServerRunOptions(),
MySQLOptions: genericoptions.NewMySQLOptions(),
InsecuresServing: genericoptions.NewInsecureServerOptions(),
RedisOptions: genericoptions.NewRedisOptions(),
Log: logger.NewOptions(),
SmsOptions: genericoptions.NewSmsOptions(),
}
return &o
}Load the configuration with Viper:
func AddConfigToOptions(options *options.Options) error {
viper.SetConfigName("config")
viper.AddConfigPath("config/")
viper.SetConfigType("yaml")
err := viper.ReadInConfig()
if err != nil {
return err
}
optDecode := viper.DecodeHook(mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
StringToByteSizeHookFunc(),
))
err = viper.Unmarshal(options, optDecode)
if err != nil {
return err
}
return nil
}Implement the SMS client using a functional‑option pattern:
type SmsClient struct {
Credential *common.Credential
Region string
Cpf *profile.ClientProfile
Request SmsRequest
}
...
func NewSmsClient(options ...func(*SmsClient)) *SmsClient {
client := &SmsClient{
Region: "ap-guangzhou",
Cpf: profile.NewClientProfile(),
}
for _, option := range options {
option(client)
}
return client
}
...
func (s *SmsClient) Send() bool {
sendClient, _ := sms.NewClient(s.Credential, s.Region, s.Cpf)
_, err := sendClient.SendSms(s.Request.request)
if _, ok := err.(*errors.TencentCloudSDKError); ok {
logger.Warnf("An API error has returned: %s", err)
return false
}
if err != nil {
logger.Warnf("发送短信失败:%s,requestId:%s", err)
return false
}
logger.Info("发送短信验证码成功")
return true
}Create request objects and helper options for phone numbers and template parameters:
type SmsRequest struct {
request *sms.SendSmsRequest
}
func NewSmsRequest(options *options.SmsOptions, withOptions ...func(*SmsRequest)) *SmsRequest {
request := sms.NewSendSmsRequest()
request.SmsSdkAppId = &options.SmsSdkAppId
request.SignName = &options.SignName
request.TemplateId = &options.TemplateId
smsRequest := &SmsRequest{request: request}
for _, option := range withOptions {
option(smsRequest)
}
return smsRequest
}
func WithPhoneNumberSet(phoneSet []string) RequestOption {
return func(smsRequest *SmsRequest) {
smsRequest.request.PhoneNumberSet = common.StringPtrs(phoneSet)
}
}
func WithTemplateParamSet(templateSet []string) RequestOption {
return func(smsRequest *SmsRequest) {
smsRequest.request.TemplateParamSet = common.StringPtrs(templateSet)
}
}In the service layer, generate a random six‑digit code, send the SMS, and store the code in Redis for later verification:
func (u *userService) SendPhoneCode(ctx context.Context, phone string) bool {
smsSetting := global.TencenSmsSetting
phoneSet := []string{phone}
randCode := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
templateSet := []string{randCode, "60"}
smsRequest := tencenSms.NewSmsRequest(smsSetting, tencenSms.WithPhoneNumberSet(phoneSet), tencenSms.WithTemplateParamSet(templateSet))
smsClient := tencenSms.NewSmsClient(tencenSms.WithRequest(*smsRequest), tencenSms.WithCredential(*smsSetting))
go smsClient.Send()
_ = u.cache.UserCaches().SetSendPhoneCodeCache(ctx, phone, randCode)
return true
}Finally, verify the code during login by comparing the cached value:
func (u *userService) LoginByPhoneCode(ctx context.Context, phone, phoneCode string) (*model.User, error) {
cacheCode, err := u.cache.UserCaches().GetSendPhoneCodeFromCache(ctx, phone)
if err != nil {
return nil, errors.WithCode(code.ErrUserPhoneCodeExpire, err.Error())
}
if cacheCode != phoneCode {
return nil, errors.WithCode(code.ErrUserPhoneCodeMiss, "")
}
return &model.User{Nickname: "lala"}, nil
}Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
