formatter.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
  7. "github.com/spf13/cast"
  8. "strconv"
  9. )
  10. type FormatterService interface {
  11. FormatBackendData(ctx context.Context, req *v1.GameShieldSubmitRequest) (string, error)
  12. }
  13. func NewFormatterService(
  14. service *Service,
  15. gameShieldPublicIpService GameShieldPublicIpService,
  16. ) FormatterService {
  17. return &formatterService{
  18. Service: service,
  19. gameShieldPublicIpService: gameShieldPublicIpService,
  20. }
  21. }
  22. type formatterService struct {
  23. *Service
  24. gameShieldPublicIpService GameShieldPublicIpService
  25. }
  26. func (service *formatterService) FormatBackendData(ctx context.Context, req *v1.GameShieldSubmitRequest) (string, error) {
  27. output := make(map[string]map[string]interface{})
  28. var userIp string
  29. if !req.Checked {
  30. var err error
  31. userIp, err = service.gameShieldPublicIpService.GetUserIp(ctx, req.Uid)
  32. if err != nil {
  33. return "", err
  34. }
  35. }
  36. if len(req.Data) == 0 {
  37. return "", fmt.Errorf("data is required")
  38. }
  39. // 解析 JSON 数据为 map[string]map[string]interface{}
  40. var backend map[string]map[string]interface{}
  41. if err := json.Unmarshal([]byte(req.Data), &backend); err != nil {
  42. return "", fmt.Errorf("failed to unmarshal req.Data: %w", err)
  43. }
  44. for i := 0; i < len(backend); i++ {
  45. key := "key" + strconv.Itoa(i)
  46. innerMap, ok := backend[key]
  47. if !ok {
  48. continue
  49. }
  50. addr := fmt.Sprintf("%s:%s", innerMap["source_machineIP"], cast.ToString(innerMap["connect_port"]))
  51. itemMap := map[string]interface{}{
  52. "addr": []string{addr},
  53. "protocol": innerMap["protocol"],
  54. }
  55. if host, ok := innerMap["host"]; ok && host != "" {
  56. itemMap["host"] = host
  57. }
  58. if innerMap["protocol"] != "udp" {
  59. if req.Checked {
  60. itemMap["proxy_addr"] = fmt.Sprintf("%s:%s", innerMap["source_machineIP"], "32353")
  61. } else {
  62. itemMap["proxy_addr"] = userIp + ":32353"
  63. }
  64. } else {
  65. itemMap["proxy_addr"] = ""
  66. itemMap["udp_session_timeout"] = "300s"
  67. }
  68. if sdkPort, ok := innerMap["sdk_port"]; ok {
  69. itemMap["sdk_port"] = sdkPort
  70. } else {
  71. itemMap["sdk_port"] = 0
  72. }
  73. output[key] = itemMap
  74. }
  75. jsonBytes, err := json.Marshal(output)
  76. if err != nil {
  77. return "", err
  78. }
  79. return string(jsonBytes), nil
  80. }