-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
49 lines (38 loc) · 1.2 KB
/
main.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
package main
// These are just a few snippets. Read more under:
// https://medium.com/statuscode/how-i-write-go-http-services-after-seven-years-37c208122831
// Shared dependencies are fields of the structure; Handlers hang off the server.
type server struct {
db *someDatabase
router *someRouter
email EmailSender
}
func (s *server) handleSomething() http.HandlerFunc { ... }
// routes.go
func (s *server) routes() {
s.router.HandleFunc("/api/", s.handleAPI())
s.router.HandleFunc("/about", s.handleAbout())
s.router.HandleFunc("/", s.handleIndex())
s.router.HandleFunc("/admin", s.adminOnly(s.handleAdminIndex()))}
// Middleware are just Go functions
func (s *server) adminOnly(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !currentUser(r).IsAdmin {
http.NotFound(w, r)
return
}
h(w, r)
}
}
// request and response types specific to a function
func (s *server) handleSomething() http.HandlerFunc {
type request struct {
Name string
}
type response struct {
Greeting string `json:"greeting"`
}
return func(w http.ResponseWriter, r *http.Request) {
...
}
}