github.com/oarkflow/sio@v0.0.6/adapters/transmission.go (about)

     1  package adapters
     2  
     3  import (
     4  	"encoding/base64"
     5  	"encoding/json"
     6  	"errors"
     7  	"log/slog"
     8  )
     9  
    10  const (
    11  	ttErr int = iota
    12  	ttStr
    13  	ttBin
    14  	ttJSON
    15  )
    16  
    17  var (
    18  	ErrBadDataType = errors.New("bad data type")
    19  	ErrNoEventName = errors.New("no event name")
    20  )
    21  
    22  type transmission struct {
    23  	DataType   int    `json:"d"`
    24  	EventName  string `json:"e"`
    25  	RoomName   string `json:"r,omitempty"`
    26  	Payload    string `json:"p"`
    27  	ServerName string `json:"s"`
    28  	Data       any    `json:"-"`
    29  }
    30  
    31  func (t *transmission) toJSON() ([]byte, error) {
    32  	data, dType := GetDataType(t.Data)
    33  	t.Payload = base64.StdEncoding.EncodeToString(data)
    34  	t.DataType = dType
    35  
    36  	return json.Marshal(t)
    37  }
    38  
    39  func (t *transmission) fromJSON(data []byte) error {
    40  	err := json.Unmarshal(data, t)
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	if t.DataType == ttErr {
    46  		return ErrBadDataType
    47  	}
    48  
    49  	if t.EventName == "" {
    50  		return ErrNoEventName
    51  	}
    52  
    53  	d, err := base64.StdEncoding.DecodeString(t.Payload)
    54  	if err != nil {
    55  		return err
    56  	}
    57  
    58  	switch t.DataType {
    59  	case ttStr:
    60  		t.Data = string(d)
    61  	case ttBin:
    62  		t.Data = d
    63  	case ttJSON:
    64  		err = json.Unmarshal(d, &t.Data)
    65  		if err != nil {
    66  			return err
    67  		}
    68  	}
    69  
    70  	return nil
    71  }
    72  
    73  func GetDataType(in any) ([]byte, int) {
    74  	switch i := in.(type) {
    75  	case string:
    76  		return []byte(i), ttStr
    77  	case []byte:
    78  		return i, ttBin
    79  	default:
    80  		j, err := json.Marshal(i)
    81  		if err != nil {
    82  			slog.Error(err.Error())
    83  			return []byte{}, ttStr
    84  		}
    85  		return j, ttJSON
    86  	}
    87  }