1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- package nats
- import (
- "Ic_ouath/configs"
- "Ic_ouath/simple_zap"
- "Ic_ouath/utils"
- "context"
- "fmt"
- "github.com/bytedance/sonic"
- "github.com/nats-io/nats.go"
- )
- var Nats *nats.Conn
- // UserResponse 定义响应结构体
- type UserResponse struct {
- Code int `json:"code"`
- Message string `json:"message"`
- User any `json:"user,omitempty"`
- }
- func SetupNats() {
- var err error
- Nats, err = nats.Connect(configs.Config.GetString("nats.url"))
- //Nats, err = nats.Connect("nats://116.204.6.184:4222")
- if err != nil {
- fmt.Println("nats 连接失败!")
- simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "nats 连接失败")
- panic(err)
- }
- fmt.Println("nats OK!")
- go NatsInit()
- }
- func NatsInit() {
- _, _ = Nats.Subscribe("login_token_validation", func(msg *nats.Msg) {
- // fmt.Println("login_token_validation msg:", string(msg.Data))
- verification, user := utils.Verification(string(msg.Data))
- response := UserResponse{
- Code: 0,
- Message: "",
- User: nil,
- }
- if verification {
- response.Code = 200
- response.Message = "success"
- response.User = user
- } else {
- response.Code = 201
- response.Message = "请重新登录"
- response.User = user
- }
- marshal, err := sonic.Marshal(response)
- if err != nil {
- fmt.Println("nats 响应失败!")
- panic(err)
- }
- _ = Nats.Publish(msg.Reply, marshal)
- })
- }
|