forked from sionide21/Go2Lunch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.go
133 lines (112 loc) · 2.35 KB
/
common.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
package main
import (
"strconv"
"bytes"
"encoding/base64"
"os"
"json"
"fmt"
)
type Byter interface {
Byte() []byte
}
type StringArgs struct {
Auth
String string
}
func (a *StringArgs) Byte() []byte {
b := bytes.NewBufferString(a.String)
return b.Bytes()
}
type IntArgs struct {
Auth
Num int
}
func (a *IntArgs) Byte() []byte {
b := bytes.NewBufferString(strconv.Itoa(a.Num))
return b.Bytes()
}
type EmptyArgs struct {
Auth
}
func (a *EmptyArgs) Byte() []byte {
return make([]byte, 1)
}
type Person struct {
CanDrive bool
Name string
NumSeats int
NominationsLeft uint
Comment string
}
func (p *Person) String() string {
str := p.Name
if p.CanDrive {
str += " [" + strconv.Itoa(p.NumSeats) + " seats]"
}
if p.Comment != "" {
str += " -- " + p.Comment
}
return str
}
func (p *Person) UnmarshalJSON(data []byte) os.Error {
person := make(map[string]interface{})
err := json.Unmarshal(data, &person)
fmt.Println("JSON:", person)
return err
}
type Place struct {
Id int
Name string
Votes uint
People PersonVector
Nominator *Person
}
func (p *Place) UnmarshalJSON(data []byte) os.Error {
place := make(map[string]interface{})
err := json.Unmarshal(data, &place)
fmt.Println("JSON:", place)
return err
}
type Bin []byte
func (b Bin) MarshalJSON() ([]byte, os.Error) {
encoded := make([]byte, 2+base64.StdEncoding.EncodedLen(len(b)))
base64.StdEncoding.Encode(encoded[1:], b)
encoded[0] = '"'
encoded[len(encoded)-1] = '"'
return encoded, nil
}
func (b *Bin) UnmarshalJSON(val []byte) os.Error {
data := val[1 : len(val)-1]
decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data)))
n, err := base64.StdEncoding.Decode(decoded, data)
if err != nil {
return err
}
*b = decoded[0:n]
return nil
}
type Auth struct {
Name string
Mac, CChallenge, SChallenge *Bin
}
func (p *Place) String() string {
nomName := "nobody"
if p.Nominator != nil {
nomName = p.Nominator.Name
}
str := strconv.Itoa(p.Id) + ") " + p.Name + " : " + nomName + " [" + strconv.Uitoa(p.Votes) + " votes]"
for _, person := range p.People {
str += "\n - " + person.String()
}
return str
}
func (p *Place) RemovePerson(name string) *Person {
for i, e := range p.People {
if e.Name == name {
defer p.People.Delete(i)
return p.People.At(i)
}
}
return &Person{}
}