This repository has been archived by the owner on Dec 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
69 lines (53 loc) · 1.54 KB
/
server.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
package main
import "net/http"
// ---
// server type
type server struct {
// eliminates global variables
db *dbConn
router *router
email EmailSender
}
// ---
// server constructor
// newServer is inconsistent with example in main.go. Matt prefers not to have
// constructors, but says he always seems to end up with one for servers
func newServer() *server {
s := &server{} // leaves dependencies as nil (could be passed as
// arguments if not many, but better to explicily assign)
s.routes()
return s
}
// ---
// server as http.Handler
// ServeHTTP makes server an http.Handler. (Recall this method is intended to
// panic instead of returning an error.)
func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.router.ServeHTTP(w, r) // delegates to router for actual implementation
// don't put logic in here, use middleware instead
}
// ---
// multiple server types
// a pattern for large apps; can have different dependencies
// in people.go
type serverPeople struct {
db *dbConn
email EmailSender
}
// comments.go
type serverComments struct {
db *dbConn
// lacks EmailSender dependencies
}
// ---
// ANCILLARY STUBS (to make compiler happy)
// Conn is a an arbitrary database connection stub
type dbConn struct{}
// EmailSender is probably an interface because name is verb
type EmailSender interface {
Send() error
}
// emailSender is an implementation of EmailSender
type emailSender struct{}
// Send is a stub function to give Sender something to match EmailSender
func (e emailSender) Send() (err error) { return err }