Nats.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package nats
  2. import (
  3. "Ic_ouath/configs"
  4. "Ic_ouath/simple_zap"
  5. "Ic_ouath/utils"
  6. "context"
  7. "fmt"
  8. "github.com/bytedance/sonic"
  9. "github.com/nats-io/nats.go"
  10. )
  11. var Nats *nats.Conn
  12. // UserResponse 定义响应结构体
  13. type UserResponse struct {
  14. Code int `json:"code"`
  15. Message string `json:"message"`
  16. User any `json:"user,omitempty"`
  17. }
  18. func SetupNats() {
  19. var err error
  20. Nats, err = nats.Connect(configs.Config.GetString("nats.url"))
  21. //Nats, err = nats.Connect("nats://116.204.6.184:4222")
  22. if err != nil {
  23. fmt.Println("nats 连接失败!")
  24. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "nats 连接失败")
  25. panic(err)
  26. }
  27. fmt.Println("nats OK!")
  28. go NatsInit()
  29. }
  30. func NatsInit() {
  31. _, _ = Nats.Subscribe("login_token_validation", func(msg *nats.Msg) {
  32. // fmt.Println("login_token_validation msg:", string(msg.Data))
  33. verification, user := utils.Verification(string(msg.Data))
  34. response := UserResponse{
  35. Code: 0,
  36. Message: "",
  37. User: nil,
  38. }
  39. if verification {
  40. response.Code = 200
  41. response.Message = "success"
  42. response.User = user
  43. } else {
  44. response.Code = 201
  45. response.Message = "请重新登录"
  46. response.User = user
  47. }
  48. marshal, err := sonic.Marshal(response)
  49. if err != nil {
  50. fmt.Println("nats 响应失败!")
  51. panic(err)
  52. }
  53. _ = Nats.Publish(msg.Reply, marshal)
  54. })
  55. }