github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/common/rpc_container.go (about)

     1  package common
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/clubpay/ronykit/kit"
     7  	"github.com/goccy/go-json"
     8  )
     9  
    10  var inPool sync.Pool
    11  
    12  // simpleIncomingJSONRPC implements kit.IncomingRPCContainer
    13  type simpleIncomingJSONRPC struct {
    14  	ID      string            `json:"id"`
    15  	Header  map[string]string `json:"hdr"`
    16  	Payload json.RawMessage   `json:"payload"`
    17  }
    18  
    19  func SimpleIncomingJSONRPC() kit.IncomingRPCContainer {
    20  	v, ok := inPool.Get().(*simpleIncomingJSONRPC)
    21  	if !ok {
    22  		v = &simpleIncomingJSONRPC{
    23  			Header: make(map[string]string, 4),
    24  		}
    25  	}
    26  
    27  	return v
    28  }
    29  
    30  func (e *simpleIncomingJSONRPC) GetID() string {
    31  	return e.ID
    32  }
    33  
    34  func (e *simpleIncomingJSONRPC) Unmarshal(data []byte) error {
    35  	return json.Unmarshal(data, e)
    36  }
    37  
    38  func (e *simpleIncomingJSONRPC) ExtractMessage(m kit.Message) error {
    39  	return json.Unmarshal(e.Payload, m)
    40  }
    41  
    42  func (e *simpleIncomingJSONRPC) GetHdr(key string) string {
    43  	return e.Header[key]
    44  }
    45  
    46  func (e *simpleIncomingJSONRPC) GetHdrMap() map[string]string {
    47  	return e.Header
    48  }
    49  
    50  func (e *simpleIncomingJSONRPC) Release() {
    51  	for k := range e.Header {
    52  		delete(e.Header, k)
    53  	}
    54  	e.Payload = e.Payload[:0]
    55  	e.ID = e.ID[:0]
    56  
    57  	inPool.Put(e)
    58  }
    59  
    60  var outPool = sync.Pool{}
    61  
    62  // simpleOutgoingJSONRPC implements kit.OutgoingRPCContainer
    63  type simpleOutgoingJSONRPC struct {
    64  	ID      string            `json:"id"`
    65  	Header  map[string]string `json:"hdr"`
    66  	Payload kit.Message       `json:"payload"`
    67  }
    68  
    69  func SimpleOutgoingJSONRPC() kit.OutgoingRPCContainer {
    70  	v, ok := outPool.Get().(*simpleOutgoingJSONRPC)
    71  	if !ok {
    72  		v = &simpleOutgoingJSONRPC{
    73  			Header: make(map[string]string, 4),
    74  		}
    75  	}
    76  
    77  	return v
    78  }
    79  
    80  func (e *simpleOutgoingJSONRPC) SetID(id string) {
    81  	e.ID = id
    82  }
    83  
    84  func (e *simpleOutgoingJSONRPC) SetHdr(k, v string) {
    85  	e.Header[k] = v
    86  }
    87  
    88  func (e *simpleOutgoingJSONRPC) InjectMessage(m kit.Message) {
    89  	e.Payload = m
    90  }
    91  
    92  func (e *simpleOutgoingJSONRPC) Marshal() ([]byte, error) {
    93  	return json.Marshal(e)
    94  }
    95  
    96  func (e *simpleOutgoingJSONRPC) Release() {
    97  	for k := range e.Header {
    98  		delete(e.Header, k)
    99  	}
   100  	e.Payload = nil
   101  	e.ID = e.ID[:0]
   102  
   103  	outPool.Put(e)
   104  }