Nats.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package Nats
  2. import (
  3. "ColdP_server/conf"
  4. "ColdP_server/controllers/lib"
  5. "ColdP_server/models/Account"
  6. "fmt"
  7. "github.com/nats-io/nats.go"
  8. "github.com/vmihailenco/msgpack/v5"
  9. "time"
  10. )
  11. func Init() {
  12. fmt.Println("============Nats init============")
  13. var err error
  14. // 连接Nats服务器
  15. lib.Nats, err = nats.Connect("nats://" + conf.NatsServer_Url)
  16. if err != nil {
  17. fmt.Println("nats 连接失败!")
  18. panic(err)
  19. }
  20. fmt.Println("nats OK!")
  21. }
  22. func Verification(GetCookie string, GetString string) (bool, Account.Admin) {
  23. Admin_tokey := GetCookie
  24. if len(Admin_tokey) == 0 {
  25. Admin_tokey = GetString
  26. }
  27. if len(Admin_tokey) == 0 {
  28. return false, Account.Admin{}
  29. }
  30. // 请求-响应, 向 verification 发布一个 `ToKey` 请求数据,设置超时间3秒,如果有多个响应,只接收第一个收到的消息
  31. msg, err := lib.Nats.Request("Cold_Admin_verification", []byte(Admin_tokey), 3*time.Second)
  32. if err != nil {
  33. return false, Account.Admin{}
  34. }
  35. fmt.Printf("Cold_Admin_verification : %s\n", string(msg.Data))
  36. type T_R struct {
  37. Code int16 `xml:"Code"`
  38. Msg string `xml:"Msg"`
  39. Data Account.Admin `xml:"Data"` // 泛型
  40. }
  41. var t_R T_R
  42. err = msgpack.Unmarshal(msg.Data, &t_R)
  43. if err != nil || t_R.Code != 200 {
  44. return false, Account.Admin{}
  45. }
  46. return true, t_R.Data
  47. }