forked from adrianco/spigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gotocol.go
81 lines (73 loc) · 2.07 KB
/
gotocol.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
// Package gotocol provides protocol support to send a variety of commands
// listener channels and types over a single channel type
package gotocol
import (
"fmt"
"time"
)
// Impositions is the promise theory term for requests made to a service
type Impositions int
// Constant definitions for message types to be imposed on the receiver
const (
// Hello ChanToParent NameForPirate // initial noodly touch
Hello Impositions = iota
// NameDrop ChanToBuddy NameOfBuddy // here's someone to talk to
NameDrop
// Chat - ThisOften // chat to buddies time interval
Chat
// GoldCoin FromChan HowMuch
GoldCoin
// Inform loggerChan text message
Inform
// GetRequest FromChan key // simulate http inbound request
GetRequest
// GetResponse FromChan value // simulate http outbound response
GetResponse
// Put - "key value" // save the key and value
Put
// Goodbye - - // tell FSM and exit
Goodbye // test assumes this is the last and exits
numOfImpositions
)
// String handler to make imposition types printable
func (imps Impositions) String() string {
switch imps {
case Hello:
return "Hello"
case NameDrop:
return "NameDrop"
case Chat:
return "Chat"
case GoldCoin:
return "GoldCoin"
case Inform:
return "Inform"
case GetRequest:
return "GetRequest"
case GetResponse:
return "GetResponse"
case Put:
return "Put"
case Goodbye:
return "Goodbye"
}
return "Unknown"
}
// Message structure used for all messages, includes a channel of itself
type Message struct {
Imposition Impositions // request type
ResponseChan chan Message // place to send response messages
Sent time.Time // time at which message was sent
Intention string // payload
}
func (msg Message) String() string {
return fmt.Sprintf("gotocol: %v %v %v", time.Since(msg.Sent), msg.Imposition, msg.Intention)
}
// Send a synchronous message
func Send(to chan<- Message, msg Message) {
to <- msg
}
// GoSend asynchronous message send, parks it on a new goroutine until it completes
func (msg Message) GoSend(to chan Message) {
go func(c chan Message, m Message) { c <- m }(to, msg)
}