/
main.go
64 lines (53 loc) · 1.67 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Package main same as api_handler_1 but with a common middleware
// NOTE, as listed on the book, .API is not a method I like to discuss, I coded this only for newcomers, it's slow and not recomemnded to use
// Use .Get/.Post/.Put/.Delete/.Head/.Connect/.Options/.Any instead.
package main
import (
"github.com/kataras/iris"
)
type UserAPI struct {
*iris.Context
}
// GET /users
func (u UserAPI) Get() {
u.WriteString("Get from /users")
// u.JSON(iris.StatusOK,myDb.AllUsers())
}
// GET /:param1 which its value passed to the id argument
func (u UserAPI) GetBy(id string) { // id equals to u.Param("param1")
u.Writef("Get from /users/%s", id)
// u.JSON(iris.StatusOK, myDb.GetUserById(id))
}
// PUT /users
func (u UserAPI) Put() {
name := u.FormValue("name")
// myDb.InsertUser(...)
println(string(name))
println("Put from /users")
}
// POST /users/:param1
func (u UserAPI) PostBy(id string) {
name := u.PostValue("name") // you can still use the whole Context's features!
// myDb.UpdateUser(...)
println(string(name))
println("Post from /users/" + id)
}
// DELETE /users/:param1
func (u UserAPI) DeleteBy(id string) {
// myDb.DeleteUser(id)
println("Delete from /" + id)
}
func main() {
iris.API("/users", UserAPI{}, myUsersMiddleware1, myUsersMiddleware2)
iris.Listen(":8080")
}
func myUsersMiddleware1(ctx *iris.Context) {
println("From users middleware 1 ")
ctx.Next()
}
func myUsersMiddleware2(ctx *iris.Context) {
println("From users middleware 2 ")
ctx.Next()
}
// NOTE, as listed on the book, .API is not a method I like to discuss, I coded this only for newcomers, it's slow and not recomemnded to use
// Use .Get/.Post/.Put/.Delete/.Head/.Connect/.Options/.Any instead.