-
Notifications
You must be signed in to change notification settings - Fork 9
/
simpleserver_4.go
151 lines (125 loc) · 3.21 KB
/
simpleserver_4.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
package main
import (
"encoding/json"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
var msg = "Dr. Who say's alonzi\n"
var anothermsg = "Winter is in Season 10\n"
// Response The thing inside `` are called struct tags. Struct tags are used to attach
// meta data to a struct field. Under the hood, packages can use reflection to extract
// this meta data. For e.g. here, encoding/json package uses it to encode/decode the struct
// from and to a json. Also notice the first letter of the type and fields is capitalized.
// The front letter capitlization is Go's way of indicating that the type(and embeddded fields)
// are public.
type Response struct {
Msg string `json:"msg,omitempty"`
Anothermsg string `json:"another_msg,omitempty"`
}
// Request ...
type Request struct {
Name string `json:"name"`
}
type server struct {
httpServer *http.Server
listener net.Listener
}
func (s *server) listenAndServe() error {
listener, err := net.Listen("tcp", s.httpServer.Addr)
if err != nil {
return err
}
s.listener = listener
go s.httpServer.Serve(s.listener)
fmt.Println("Server now listening")
return nil
}
func (s *server) shutdown() error {
if s.listener != nil {
err := s.listener.Close()
s.listener = nil
if err != nil {
return err
}
}
fmt.Println("Shutting down server")
return nil
}
func newServer(port string) *server {
handle := func(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println("error reading request body", err)
return
}
// The very useful unmarshal method decodes the incoming json onto the request
// type
var request Request
err = json.Unmarshal(body, &request)
if err != nil {
log.Println("json unmarshal error", err)
return
}
log.Println("request:", request)
// Marshal encodes the struct type into a json byte[]
response := &Response{Msg: "Hello " + request.Name}
b, err := json.Marshal(response)
if err != nil {
log.Println("json marshal error", err)
return
}
log.Println("response:", string(b))
io.WriteString(w, string(b))
}
anotherhandle := func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, anothermsg)
}
mux := http.NewServeMux()
mux.HandleFunc("/", handle)
mux.HandleFunc("/another", anotherhandle)
httpServer := &http.Server{Addr: ":" + port, Handler: mux}
return &server{httpServer: httpServer}
}
func testRig(f func()) {
server := newServer("3333")
server.listenAndServe()
time.Sleep(500)
defer server.shutdown()
f()
}
func main() {
var port string
flag.StringVar(&port, "port", "3333", "./simpleserver_4 -port 3333")
flag.Parse()
sigs := make(chan os.Signal, 1)
done := make(chan bool, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
moveAlong := func() {
fmt.Println("Not the droid you lookin for...")
}
server := newServer(port)
server.listenAndServe()
defer moveAlong()
go func() {
sig := <-sigs
fmt.Println()
fmt.Println(sig)
server.shutdown()
done <- true
}()
fmt.Println("Ctrl-C to interrupt...")
<-done
fmt.Println("Exiting...")
// Take a look at simpleserver_4_test.go
// go test
// btw this file is gettig too messy. let's do something about that.
}