forked from fwhezfwhez/tcpx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
784 lines (688 loc) · 21.1 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
package tcpx
import (
"errors"
"fmt"
"github.com/fwhezfwhez/errorx"
"io"
"net"
"strings"
"sync"
"time"
)
const CONTEXT_ONLINE = 1
const CONTEXT_OFFLINE = 2
const ABORT = 2019
// Context has two concurrently safe context:
// PerConnectionContext is used for connection, once the connection is built ,this is connection scope.
// PerRequestContext is used for request, when connection was built, then many requests can be sent between client and server.
// Each request has an independently scoped context , this is PerRequestContext.
// Packx used to save a marshaller helping marshal and unMarshal stream
// Stream is read from net.Conn per request
type Context struct {
// for tcp conn
Conn net.Conn
// context scope lock
L *sync.RWMutex
// for udp conn
PacketConn net.PacketConn
Addr net.Addr
// for kcp conn
//UDPSession *kcp.UDPSession
// for k-v pair shared in connection/request scope
PerConnectionContext *sync.Map
PerRequestContext *sync.Map
// for pack and unpack
Packx *Packx
// saves a pool-ref from TcpX instance
// only when TcpX instance has set builtInPool true, poolRef is not nil
// - How to use this?
// `ctx.Online(username)`
// `ctx.Offline()`
poolRef *ClientPool
// signal end, after called `ctx.CloseConn()`, it can broadcast all routine related to this connection.
// It will ensure all related goroutine to die.
recvEnd chan int
recvAuth chan int
// 1- online, 2- offline
// This value will init to 1 by NewContext() and turn 2 by ctx.Close()
// This value is shared among request context, so it must be pointer int,not value int
userState *int
// for raw message
ConnReader io.Reader
ConnWriter io.Writer
// for request scpope,Stream, offset, handlers will be copy when new request comes(same connection)
Stream []byte
// used to control middleware abort or next
// offset == ABORT, abort
// else next
offset int
handlers []func(*Context)
}
// share some pointer properties With former context, but has independent Stream and handlers
// Not locked. Caller should lock it.
func copyContext(ctx Context) *Context {
var copyHandlers = make([]func(*Context), len(ctx.handlers))
for i, _ := range copyHandlers {
copyHandlers[i] = ctx.handlers[i]
}
return &Context{
Conn: ctx.Conn,
L: ctx.L,
PacketConn: ctx.PacketConn,
Addr: ctx.Addr,
//UDPSession: ctx.UDPSession,
PerConnectionContext: ctx.PerConnectionContext,
PerRequestContext: ctx.PerConnectionContext,
Packx: ctx.Packx,
Stream: ctx.Stream,
offset: ctx.offset,
handlers: copyHandlers,
poolRef: ctx.poolRef,
recvEnd: ctx.recvEnd,
recvAuth: ctx.recvAuth,
userState: ctx.userState,
ConnReader: ctx.ConnReader,
ConnWriter: ctx.ConnWriter,
}
}
// No strategy to ensure username repeat or not , if username exists, it will replace the old connection context in the pool.
// Only used when tcpX instance's builtInPool is true,
// otherwise you should design your own client pool(github.com/fwhezfwhez/tcpx/clientPool/client-pool.go), and manage it
// yourself, like:
// ```
// var myPool = clientPool.NewClientPool()
// func main() {
// srv := tcpx.NewTcpX(nil)
// srv.AddHandler(1, func(c *tcpx.Context){
// type Login struct{
// Username string
// }
// var userLogin Login
// c.Bind(&userLogin)
// myPool.Online(userLogin.Username, c)
// })
// srv.AddHandler(2, func(c *tcpx.Context){
// username, ok := ctx.Username()
// if !ok {
// fmt.Println("anonymous user no need to offline")
// }
// myPool.Offline(username)
// })
// }
// ```
func (ctx *Context) Online(username string) error {
if username == "" {
return errors.New("can't use empty username to online")
}
ctx.SetUsername(username)
if ctx.poolRef == nil {
return errors.New("ctx.poolRef is nil, did you call 'tcpX.WithBuiltInPool(true)' or 'tcpX.SetPool(pool *tcpx.ClientPool)' yet")
}
ctx.poolRef.Online(username, ctx)
return nil
}
// Only used when tcpX instance's builtInPool is true,
// otherwise you should design your own client pool(github.com/fwhezfwhez/tcpx/clientPool/client-pool.go), and manage it
// yourself, like:
// ```
// var myPool = clientPool.NewClientPool()
// func main() {
// srv := tcpx.NewTcpX(nil)
// srv.AddHandler(1, func(c *tcpx.Context){
// type Login struct{
// Username string
// }
// var userLogin Login
// c.Bind(&userLogin)
// myPool.Online(userLogin.Username, c)
// })
// srv.AddHandler(2, func(c *tcpx.Context){
// myPool.Offline(userLogin.Username)
// })
// }
//```
func (ctx *Context) Offline() error {
if ctx.poolRef == nil {
return errors.New("ctx.poolRef is nil, did you call 'tcpX.WithBuiltInPool(true)' or 'tcpX.SetPool(pool *tcpx.ClientPool)' yet")
}
username, ok := ctx.Username()
if !ok {
return errors.New("offline username empty, did you call c.Online(username string) yet")
}
ctx.poolRef.Offline(username)
return nil
}
// New a context.
// This is used for new a context for tcp server.
func NewContext(conn net.Conn, marshaller Marshaller) *Context {
var online = CONTEXT_ONLINE
return &Context{
Conn: conn,
PerConnectionContext: &sync.Map{},
PerRequestContext: &sync.Map{},
Packx: NewPackx(marshaller),
offset: -1,
recvEnd: make(chan int, 1),
recvAuth: make(chan int, 1),
L: &sync.RWMutex{},
userState: &online,
}
}
// New a context.
// This is used for new a context for tcp server.
func NewTCPContext(conn net.Conn, marshaller Marshaller) *Context {
return NewContext(conn, marshaller)
}
// New a context.
// This is used for new a context for udp server.
func NewUDPContext(conn net.PacketConn, addr net.Addr, marshaller Marshaller) *Context {
var online = CONTEXT_ONLINE
return &Context{
PacketConn: conn,
Addr: addr,
PerConnectionContext: nil,
PerRequestContext: &sync.Map{},
Packx: NewPackx(marshaller),
offset: -1,
recvEnd: make(chan int, 1),
recvAuth: make(chan int, 1),
L: &sync.RWMutex{},
userState: &online,
}
}
// New a context.
// This is used for new a context for kcp server.
//func NewKCPContext(udpSession *kcp.UDPSession, marshaller Marshaller) *Context {
// var online = CONTEXT_ONLINE
// return &Context{
// UDPSession: udpSession,
// PerConnectionContext: nil,
// PerRequestContext: &sync.Map{},
//
// Packx: NewPackx(marshaller),
// offset: -1,
//
// recvEnd: make(chan int, 1),
// recvAuth: make(chan int, 1),
//
// L: &sync.RWMutex{},
// userState: &online,
// }
//}
// ConnectionProtocol returns server protocol, tcp, udp, kcp
func (ctx *Context) ConnectionProtocolType() string {
if ctx.Conn != nil {
return "tcp"
}
if ctx.Addr != nil && ctx.PacketConn != nil {
return "udp"
}
//if ctx.UDPSession != nil {
// return "kcp"
//}
return "tcp"
}
func (ctx *Context) InitReaderAndWriter() error {
switch ctx.ConnectionProtocolType() {
case "tcp":
ctx.ConnReader = ctx.Conn
ctx.ConnWriter = ctx.Conn
//case "kcp":
// ctx.ConnReader = ctx.UDPSession
// ctx.ConnWriter = ctx.UDPSession
// udp not support writer and reader
//case "udp":
// ctx.ConnReader = ctx.PacketConn
// ctx.ConnWriter = ctx.PacketConn
default:
return fmt.Errorf("only accept tcp/kcp but got %s", ctx.ConnectionProtocolType())
}
return nil
}
// Close its connection
func (ctx *Context) CloseConn() error {
defer func() {
if ctx.recvEnd != nil {
CloseChanel(func() {
close(ctx.recvEnd)
})
}
if ctx.poolRef != nil {
ctx.Offline()
}
ctx.L.Lock()
defer ctx.L.Unlock()
*(ctx.userState) = CONTEXT_OFFLINE
}()
switch ctx.ConnectionProtocolType() {
case "tcp":
return ctx.Conn.Close()
case "udp":
return ctx.PacketConn.Close()
//case "kcp":
// return ctx.UDPSession.Close()
}
return nil
}
// set deadline
func (ctx *Context) SetDeadline(t time.Time) error {
switch ctx.ConnectionProtocolType() {
case "tcp":
return ctx.Conn.SetDeadline(t)
case "udp":
return ctx.PacketConn.SetDeadline(t)
//case "kcp":
// return ctx.UDPSession.SetDeadline(t)
}
return nil
}
// set read deadline
func (ctx *Context) SetReadDeadline(t time.Time) error {
switch ctx.ConnectionProtocolType() {
case "tcp":
return ctx.Conn.SetReadDeadline(t)
case "udp":
return ctx.PacketConn.SetReadDeadline(t)
//case "kcp":
// return ctx.UDPSession.SetReadDeadline(t)
}
return nil
}
// set write deadline
func (ctx *Context) SetWriteDeadline(t time.Time) error {
switch ctx.ConnectionProtocolType() {
case "tcp":
return ctx.Conn.SetWriteDeadline(t)
case "udp":
return ctx.PacketConn.SetWriteDeadline(t)
//case "kcp":
// return ctx.UDPSession.SetWriteDeadline(t)
}
return nil
}
func (ctx *Context) Bind(dest interface{}) (Message, error) {
return ctx.Packx.Unpack(ctx.Stream, dest)
}
// When context serves for tcp, set context k-v pair of PerConnectionContext.
// When context serves for udp, set context k-v pair of PerRequestContext
// Key should not start with 'tcpx-', or it will panic.
func (ctx *Context) SetCtxPerConn(k, v interface{}) {
if tmp, ok := k.(string); ok {
if strings.HasPrefix(tmp, "tcpx-") {
panic("keys starting with 'tcpx-' are not allowed setting, they're used officially inside")
}
}
if ctx.ConnectionProtocolType() == "udp" {
ctx.SetCtxPerRequest(k, v)
return
}
ctx.PerConnectionContext.Store(k, v)
}
// Context's connection scope saves an unique key to the connection pool
// Before using this, ctx.SetUsername should be call first
func (ctx *Context) Username() (string, bool) {
usernameI, ok := ctx.GetCtxPerConn("tcpx-username")
if !ok {
return "", ok
}
return usernameI.(string), ok
}
// Context's connection scope saves an unique key to the connection pool
// Before using this, ctx.SetUsername should be call first
func (ctx *Context) GetUsername() (string) {
usernameI, ok := ctx.GetCtxPerConn("tcpx-username")
if !ok {
return ""
}
return usernameI.(string)
}
// When you want to tag an username to the context, use it, or it will be regarded as an anonymous user
func (ctx *Context) SetUsername(username string) {
ctx.setCtxPerConn("tcpx-username", username)
}
// this has no restriction for key, should be used in local package
func (ctx *Context) setCtxPerConn(k, v interface{}) {
if ctx.ConnectionProtocolType() == "udp" {
ctx.SetCtxPerRequest(k, v)
return
}
ctx.PerConnectionContext.Store(k, v)
}
// When context serves for tcp, get context k-v pair of PerConnectionContext.
// When context serves for udp, get context k-v pair of PerRequestContext.
func (ctx *Context) GetCtxPerConn(k interface{}) (interface{}, bool) {
if ctx.ConnectionProtocolType() == "udp" {
return ctx.GetCtxPerRequest(k)
}
return ctx.PerConnectionContext.Load(k)
}
func (ctx *Context) SetCtxPerRequest(k, v interface{}) {
ctx.PerRequestContext.Store(k, v)
}
func (ctx *Context) GetCtxPerRequest(k interface{}) (interface{}, bool) {
return ctx.PerRequestContext.Load(k)
}
// Reply to client using ctx's well-set Packx.Marshaller.
func (ctx *Context) Reply(messageID int32, src interface{}, headers ...map[string]interface{}) error {
var buf []byte
var e error
buf, e = ctx.Packx.Pack(messageID, src, headers ...)
if e != nil {
return errorx.Wrap(e)
}
return ctx.replyBuf(buf)
}
func (ctx *Context) ReplyWithMarshaller(marshaller Marshaller, messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReplyWithMarshaller(marshaller, messageID, src, headers...)
}
// Reply to client using json marshaller.
// Whatever ctx.Packx.Marshaller.MarshalName is 'json' or not , message block will marshal its header and body by json marshaller.
func (ctx *Context) JSON(messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReply("json", messageID, src, headers...)
}
// Reply to client using xml marshaller.
// Whatever ctx.Packx.Marshaller.MarshalName is 'xml' or not , message block will marshal its header and body by xml marshaller.
func (ctx *Context) XML(messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReply("xml", messageID, src, headers...)
}
// Reply to client using toml marshaller.
// Whatever ctx.Packx.Marshaller.MarshalName is 'toml' or not , message block will marshal its header and body by toml marshaller.
func (ctx *Context) TOML(messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReply("toml", messageID, src, headers...)
}
// Reply to client using yaml marshaller.
// Whatever ctx.Packx.Marshaller.MarshalName is 'yaml' or not , message block will marshal its header and body by yaml marshaller.
func (ctx *Context) YAML(messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReply("yaml", messageID, src, headers...)
}
// Reply to client using protobuf marshaller.
// Whatever ctx.Packx.Marshaller.MarshalName is 'protobuf' or not , message block will marshal its header and body by protobuf marshaller.
func (ctx *Context) ProtoBuf(messageID int32, src interface{}, headers ...map[string]interface{}) error {
return ctx.commonReply("protobuf", messageID, src, headers...)
}
func (ctx *Context) commonReply(marshalName string, messageID int32, src interface{}, headers ...map[string]interface{}) error {
var buf []byte
var e error
var marshaller Marshaller
if ctx.Packx.Marshaller.MarshalName() != marshalName {
marshaller, e = GetMarshallerByMarshalName(marshalName)
if e != nil {
return errorx.Wrap(e)
}
buf, e = NewPackx(marshaller).Pack(messageID, src, headers...)
if e != nil {
return errorx.Wrap(e)
}
e = ctx.replyBuf(buf)
if e != nil {
return errorx.Wrap(e)
}
return nil
}
buf, e = ctx.Packx.Pack(messageID, src, headers ...)
if e != nil {
return errorx.Wrap(e)
}
return ctx.replyBuf(buf)
}
func (ctx *Context) commonReplyWithMarshaller(marshaller Marshaller, messageID int32, src interface{}, headers ...map[string]interface{}) error {
var buf []byte
var e error
buf, e = NewPackx(marshaller).Pack(messageID, src, headers...)
if e != nil {
return errorx.Wrap(e)
}
e = ctx.replyBuf(buf)
if e != nil {
return errorx.Wrap(e)
}
return nil
}
// Divide to udp and tcp replying accesses.
func (ctx *Context) replyBuf(buf []byte) (e error) {
switch ctx.ConnectionProtocolType() {
case "tcp":
if _, e = ctx.Conn.Write(buf); e != nil {
return errorx.Wrap(e)
}
case "udp":
if _, e = ctx.PacketConn.WriteTo(buf, ctx.Addr); e != nil {
return errorx.Wrap(e)
}
//case "kcp":
// if _, e = ctx.UDPSession.Write(buf); e != nil {
// return errorx.Wrap(e)
// }
}
return nil
}
func (ctx Context) Network() string {
return ctx.ConnectionProtocolType()
}
// client ip
func (ctx Context) ClientIP() string {
var clientAddr string
switch ctx.ConnectionProtocolType() {
case "tcp":
clientAddr = ctx.Conn.RemoteAddr().String()
case "udp":
clientAddr = ctx.Addr.String()
//case "kcp":
// clientAddr = ctx.UDPSession.RemoteAddr().String()
}
arr := strings.Split(clientAddr, ":")
// ipv4
if len(arr) == 2 {
return arr[0]
}
// [::1] localhost
if strings.Contains(clientAddr, "[") && strings.Contains(clientAddr, "]") {
return "127.0.0.1"
}
// ivp6
return strings.Join(arr[:len(arr)-1], ":")
}
// stop middleware chain
func (ctx *Context) Abort() {
ctx.offset = ABORT
}
// Since middlewares are divided into 3 kinds: global, messageIDSelfRelated, anchorType,
// offset can't be used straightly to control middlewares like middlewares[offset]().
// Thus, c.Next() means actually do nothing.
func (ctx *Context) Next() {
ctx.offset ++
s := len(ctx.handlers)
for ; ctx.offset < s; ctx.offset++ {
if !ctx.isAbort() {
ctx.handlers[ctx.offset](ctx)
} else {
return
}
}
}
func (ctx *Context) ResetOffset() {
ctx.offset = -1
}
func (ctx *Context) Reset() {
ctx.PerRequestContext = &sync.Map{}
ctx.offset = -1
if ctx.handlers == nil {
ctx.handlers = make([]func(*Context), 0, 10)
return
}
ctx.handlers = ctx.handlers[:0]
}
func (ctx *Context) isAbort() bool {
if ctx.offset >= ABORT {
return true
}
return false
}
func (ctx *Context) IsOffline() bool {
ctx.L.RLock()
defer ctx.L.RUnlock()
return *(ctx.userState) == CONTEXT_OFFLINE
}
func (ctx *Context) IsOnline() bool {
if ctx == nil {
return false
}
ctx.L.RLock()
defer ctx.L.RUnlock()
return *(ctx.userState) == CONTEXT_ONLINE
}
// BindWithMarshaller will specific marshaller.
// in contract, c.Bind() will use its inner packx object marshaller
func (ctx *Context) BindWithMarshaller(dest interface{}, marshaller Marshaller) (Message, error) {
return NewPackx(marshaller).Unpack(ctx.Stream, dest)
}
// ctx.Stream is well marshaled by pack tool.
// ctx.RawStream is help to access raw stream.
func (ctx *Context) RawStream() ([]byte, error) {
return ctx.Packx.BodyBytesOf(ctx.Stream)
}
// HeartBeatChan returns a prepared chan int to save heart-beat signal.
// It will never be nil, if not exist the channel, it will auto-make.
func (ctx *Context) HeartBeatChan() chan int {
channel, ok := ctx.GetCtxPerConn("tcpx-heart-beat-channel")
if !ok {
channel = make(chan int, 1)
ctx.setCtxPerConn("tcpx-heart-beat-channel", channel)
return channel.(chan int)
} else {
tmp, ok := channel.(chan int)
if !ok {
channel = make(chan int, 1)
ctx.setCtxPerConn("tcpx-heart-beat-channel", channel)
return channel.(chan int)
}
return tmp
}
}
// RecvHeartBeat
func (ctx *Context) RecvHeartBeat() {
ctx.HeartBeatChan() <- 1
}
// Send to another conn index via username.
// Make sure called `srv.WithBuiltInPool(true)`
func (ctx *Context) SendToUsername(username string, messageID int32, src interface{}, headers ...map[string]interface{}) error {
if ctx.poolRef == nil {
return errors.New("'ctx.poolRef' is nil, make sure call 'srv.WithBuiltInPool(true)'")
}
anotherCtx := ctx.poolRef.GetClientPool(username)
if anotherCtx == nil || anotherCtx.IsOffline() {
return errors.New(fmt.Sprintf("username '%s' not found in pool, he/she might get offine", username))
}
return ctx.SendToConn(anotherCtx, messageID, src, headers...)
}
// Send to another conn via Context.
// Make sure called `srv.WithBuiltInPool(true)`
func (ctx *Context) SendToConn(anotherCtx *Context, messageID int32, src interface{}, headers ...map[string]interface{}) error {
return anotherCtx.Reply(messageID, src, headers...)
}
func (ctx *Context) GetPoolRef() *ClientPool {
ctx.L.RLock()
defer ctx.L.RUnlock()
return ctx.poolRef
}
func (ctx *Context) AuthChan() <-chan int {
return ctx.recvAuth
}
func (ctx *Context) RecvAuthPass() {
const PASS = 1
ctx.recvAuth <- PASS
}
func (ctx *Context) RecvAuthDeny() {
const DENY = -1
ctx.recvAuth <- DENY
}
// Decode ctx.Stream.Header["Router-Type"], expected 'MESSAGE_ID', 'URL_PATTERN'
func (ctx Context) RouterType() string {
rt, cached := ctx.routerType()
if !cached {
ctx.setRouterType(rt)
}
return rt
}
// return routertype, cached in ctx
func (ctx *Context) routerType() (string, bool) {
rt, exist := ctx.GetCtxPerRequest("router_type")
if exist {
rtstr, transfer := rt.(string)
if transfer {
return rtstr, true
}
}
if len(ctx.Stream) == 0 {
return MESSAGEID, false
}
header, e := HeaderOf(ctx.Stream)
if e != nil {
Logger.Println("header decode err: %s", errorx.Wrap(e).Error())
return MESSAGEID, false
}
if len(header) == 0 {
return MESSAGEID, false
}
routerTypeI, exist := header[HEADER_ROUTER_KEY]
if !exist {
return MESSAGEID, false
}
routerTypeStr, transfer := routerTypeI.(string)
if !transfer {
return MESSAGEID, false
}
if routerTypeStr == MESSAGEID {
return MESSAGEID, false
}
return routerTypeStr, false
}
// Will reply to client a message with specific url-pattern, used when message_type routing by url-pattern
func (ctx *Context) JSONURLPattern(src interface{}) error {
urlPattern, e := ctx.GetURLPattern()
if e != nil {
return errorx.Wrap(e)
}
buf, e := NewURLPatternMessage(urlPattern, src).Pack(JsonMarshaller{})
if e != nil {
return errorx.Wrap(e)
}
if e := ctx.replyBuf(buf); e != nil {
return errorx.Wrap(e)
}
return nil
}
// Will reply to client a message with specific url-pattern. Its payload is marshalled by protobuf and require src implements proto.Message.
// Used when message_type routing by url-pattern
func (ctx *Context) ProtobufURLPattern(src interface{}) error {
urlPattern, e := ctx.GetURLPattern()
if e != nil {
return errorx.Wrap(e)
}
buf, e := NewURLPatternMessage(urlPattern, src).Pack(ProtobufMarshaller{})
if e != nil {
return errorx.Wrap(e)
}
if e := ctx.replyBuf(buf); e != nil {
return errorx.Wrap(e)
}
return nil
}
func (ctx *Context) setRouterType(routerType string) {
ctx.PerRequestContext.Store("router_type", routerType)
}
func (ctx *Context) GetURLPattern() (string, error) {
urlPattern, exist := ctx.PerRequestContext.Load("url_pattern")
if exist {
urlPatternStr, transfer := urlPattern.(string)
if transfer {
return urlPatternStr, nil
}
}
urlPatternStr, e := URLPatternOf(ctx.Stream)
if e != nil {
return "", errorx.Wrap(e)
}
ctx.PerRequestContext.Store("url_pattern", urlPatternStr)
return urlPatternStr, nil
}