# 单一控制器
package main
import (
"fmt"
"sync/atomic"
"github.com/kataras/iris"
"github.com/kataras/iris/mvc"
)
func main() {
app := iris.New()
mvc.New(app.Party("/")).Handle(&globalVisitorsController{visits: 0})
// http://localhost:8080
app.Run(iris.Addr(":8080"))
}
type globalVisitorsController struct {
//当访问单一控制器的时候,由开发人员负责并发的安全访问,
// 因为所有的客户端共享一个相同的控制器实例。
// 请注意任何控制器的方法都是每个客户端的,
// 但是如果此结构没有任何动态结构字段依赖于 Iris ,该结构的字段可以在多个客户端共享。
// Context 和 ALL 字段的值不为0,在这种情况下我们使用 unit64 ,
// 它的值不是0(即使我们没有手动设置它),而是 &{0} 。
// 以上所有都声明了只有一个 Singleton ,注意你不必去写代码去实现它,Iris 已经给你做好了。
// 请看 `Get` 方法。
visits uint64
}
func (c *globalVisitorsController) Get() string {
count := atomic.AddUint64(&c.visits, 1)
return fmt.Sprintf("Total visitors: %d", count)
}
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
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
更多的文件结构指南在 https://github.com/kataras/iris/tree/master/_examples/#structuring (opens new window) 中可以找到。
请遵循以下示例
- Hello world (opens new window) UPDATED
- Session Controller (opens new window) UPDATED
- Overview - Plus Repository and Service layers (opens new window) UPDATED
- Login showcase - Plus Repository and Service layers (opens new window) UPDATED
- Singleton (opens new window) NEW
- Websocket Controller (opens new window) NEW
- Register Middleware (opens new window) NEW
- Vue.js Todo MVC (opens new window) NEW