sms_lib.go 1.4 KB
package smslib

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/gateway"
	"gitlab.fjmaimaimai.com/allied-creation/su-micro/pkg/xerr"
	"net/http"
)

type SMSService struct {
	gateway.Service
}

func (svc *SMSService) SendSmsCode(ctx context.Context, request RequestSendSmsCode) (*DataSendSmsCode, error) {
	var result DataSendSmsCode
	if err := svc.Do(ctx, "/service/sendSms", http.MethodPost, request, &result); err != nil {
		return nil, err
	}
	return &result, nil
}

func (svc *SMSService) CheckSmsCode(ctx context.Context, request RequestCheckSmsCode) (*DataCheckSmsCode, error) {
	var result DataCheckSmsCode
	if err := svc.Do(ctx, "/service/checkSmsCode", http.MethodPost, request, &result); err != nil {
		return nil, err
	}
	return &result, nil
}

func SendSmsCodeHandler(smsService SMSService) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req struct {
			Phone string `json:"phone"`
		}
		if err := httpx.Parse(r, &req); err != nil {
			httpx.Error(w, err)
			return
		}
		var (
			err error
		)
		defer func() {
			if err != nil {
				logx.Error(err)
				xerr.ErrorHandlerCtx(r.Context(), xerr.NewErrMsgErr(err.Error(), err))
			}
		}()
		_, err = smsService.SendSmsCode(r.Context(), RequestSendSmsCode{
			Phone: req.Phone,
		})
		if err != nil {
			return
		}
		httpx.Ok(w)
	}
}