formatter.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. userIp, err := service.gameShieldPublicIpService.GetUserIp(ctx, req.Uid)
  29. if err != nil {
  30. return "", err
  31. }
  32. if len(req.Data) == 0 {
  33. return "", fmt.Errorf("data is required")
  34. }
  35. // 解析 JSON 数据为 map[string]map[string]interface{}
  36. var backend map[string]map[string]interface{}
  37. if err := json.Unmarshal([]byte(req.Data), &backend); err != nil {
  38. return "", fmt.Errorf("failed to unmarshal req.Data: %w", err)
  39. }
  40. for i := 0; i < len(backend); i++ {
  41. key := "key" + strconv.Itoa(i)
  42. innerMap, ok := backend[key]
  43. if !ok {
  44. continue
  45. }
  46. addr := fmt.Sprintf("%s:%s", innerMap["source_machineIP"], cast.ToString(innerMap["connect_port"]))
  47. itemMap := map[string]interface{}{
  48. "addr": []string{addr},
  49. "protocol": innerMap["protocol"],
  50. }
  51. if host, ok := innerMap["host"]; ok && host != "" {
  52. itemMap["host"] = host
  53. }
  54. if innerMap["protocol"] != "udp" {
  55. if req.Checked == 1 {
  56. itemMap["agent_addr"] = fmt.Sprintf("%s:%s", innerMap["source_machineIP"], "23350")
  57. }
  58. itemMap["proxy_addr"] = userIp + ":32353"
  59. } else {
  60. itemMap["proxy_addr"] = ""
  61. itemMap["udp_session_timeout"] = "300s"
  62. }
  63. if sdkPort, ok := innerMap["sdk_port"]; ok {
  64. itemMap["sdk_port"] = sdkPort
  65. } else {
  66. itemMap["sdk_port"] = 0
  67. }
  68. output[key] = itemMap
  69. }
  70. jsonBytes, err := json.Marshal(output)
  71. if err != nil {
  72. return "", err
  73. }
  74. return string(jsonBytes), nil
  75. }