forked from labstack/echo
/
server.go
146 lines (117 loc) · 2.51 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
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
package main
import (
"io"
"net/http"
"html/template"
"github.com/labstack/echo"
mw "github.com/labstack/echo/middleware"
"github.com/rs/cors"
"github.com/thoas/stats"
)
type (
// Template provides HTML template rendering
Template struct {
templates *template.Template
}
user struct {
ID string `json:"id"`
Name string `json:"name"`
}
)
var (
users map[string]user
)
// Render HTML
func (t *Template) Render(w io.Writer, name string, data interface{}) error {
return t.templates.ExecuteTemplate(w, name, data)
}
//----------
// Handlers
//----------
func welcome(c *echo.Context) error {
return c.Render(http.StatusOK, "welcome", "Joe")
}
func createUser(c *echo.Context) error {
u := new(user)
if err := c.Bind(u); err != nil {
return err
}
users[u.ID] = *u
return c.JSON(http.StatusCreated, u)
}
func getUsers(c *echo.Context) error {
return c.JSON(http.StatusOK, users)
}
func getUser(c *echo.Context) error {
return c.JSON(http.StatusOK, users[c.P(0)])
}
func main() {
e := echo.New()
// Middleware
e.Use(mw.Logger())
e.Use(mw.Recover())
e.Use(mw.Gzip())
//------------------------
// Third-party middleware
//------------------------
// https://github.com/rs/cors
e.Use(cors.Default().Handler)
// https://github.com/thoas/stats
s := stats.New()
e.Use(s.Handler)
// Route
e.Get("/stats", func(c *echo.Context) error {
return c.JSON(http.StatusOK, s.Data())
})
// Serve index file
e.Index("public/index.html")
// Serve favicon
e.Favicon("public/favicon.ico")
// Serve static files
e.Static("/scripts", "public/scripts")
//--------
// Routes
//--------
e.Post("/users", createUser)
e.Get("/users", getUsers)
e.Get("/users/:id", getUser)
//-----------
// Templates
//-----------
t := &Template{
// Cached templates
templates: template.Must(template.ParseFiles("public/views/welcome.html")),
}
e.SetRenderer(t)
e.Get("/welcome", welcome)
//-------
// Group
//-------
// Group with parent middleware
a := e.Group("/admin")
a.Use(func(c *echo.Context) error {
// Security middleware
return nil
})
a.Get("", func(c *echo.Context) error {
return c.String(http.StatusOK, "Welcome admin!")
})
// Group with no parent middleware
g := e.Group("/files", func(c *echo.Context) error {
// Security middleware
return nil
})
g.Get("", func(c *echo.Context) error {
return c.String(http.StatusOK, "Your files!")
})
// Start server
e.Run(":1323")
}
func init() {
users = map[string]user{
"1": user{
ID: "1",
Name: "Wreck-It Ralph",
},
}
}