1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- package service
- import (
- "context"
- "encoding/json"
- "fmt"
- v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
- "github.com/spf13/cast"
- "strconv"
- )
- type FormatterService interface {
- FormatBackendData(ctx context.Context, req *v1.GameShieldSubmitRequest) (string, error)
- }
- func NewFormatterService(
- service *Service,
- gameShieldPublicIpService GameShieldPublicIpService,
- ) FormatterService {
- return &formatterService{
- Service: service,
- gameShieldPublicIpService: gameShieldPublicIpService,
- }
- }
- type formatterService struct {
- *Service
- gameShieldPublicIpService GameShieldPublicIpService
- }
- func (service *formatterService) FormatBackendData(ctx context.Context, req *v1.GameShieldSubmitRequest) (string, error) {
- output := make(map[string]map[string]interface{})
- userIp, err := service.gameShieldPublicIpService.GetUserIp(ctx, req.Uid)
- if err != nil {
- return "", err
- }
- if len(req.Data) == 0 {
- return "", fmt.Errorf("data is required")
- }
- // 解析 JSON 数据为 map[string]map[string]interface{}
- var backend map[string]map[string]interface{}
- if err := json.Unmarshal([]byte(req.Data), &backend); err != nil {
- return "", fmt.Errorf("failed to unmarshal req.Data: %w", err)
- }
- for i := 0; i < len(backend); i++ {
- key := "key" + strconv.Itoa(i)
- innerMap, ok := backend[key]
- if !ok {
- continue
- }
- addr := fmt.Sprintf("%s:%s", innerMap["source_machineIP"], cast.ToString(innerMap["connect_port"]))
- itemMap := map[string]interface{}{
- "addr": []string{addr},
- "protocol": innerMap["protocol"],
- }
- if host, ok := innerMap["host"]; ok && host != "" {
- itemMap["host"] = host
- }
- if innerMap["protocol"] != "udp" {
- if req.Checked == 1 {
- itemMap["agent_addr"] = fmt.Sprintf("%s:%s", innerMap["source_machineIP"], "23350")
- }
- itemMap["proxy_addr"] = userIp + ":32353"
- } else {
- itemMap["proxy_addr"] = ""
- itemMap["udp_session_timeout"] = "300s"
- }
- if sdkPort, ok := innerMap["sdk_port"]; ok {
- itemMap["sdk_port"] = sdkPort
- } else {
- itemMap["sdk_port"] = 0
- }
- output[key] = itemMap
- }
- jsonBytes, err := json.Marshal(output)
- if err != nil {
- return "", err
- }
- return string(jsonBytes), nil
- }
|