-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
84 lines (68 loc) · 1.6 KB
/
Copy pathmain.go
File metadata and controls
84 lines (68 loc) · 1.6 KB
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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/WengChaoxi/go-web-framework/framework"
"github.com/WengChaoxi/go-web-framework/framework/middleware"
)
// test
func TestHandler(c *framework.Context) error {
id := c.QueryInt("id", 0)
if id == 1 {
c.Json(200, "hello world")
} else if id == 2 {
c.Text("test")
} else if id == 3 {
c.HTML("<h1>你好世界</h1>", nil)
}
return nil
}
// default
func DefaultHandler(c *framework.Context) error {
c.Json(200, c.Request().URL.Path)
return nil
}
func main() {
core := framework.NewCore()
// 超时中间件
core.Use(middleware.Timeout(1 * time.Second))
// 注册 /test 路由
core.Get("/test", TestHandler)
// 使用 group 分组,路由前缀
userRouter := core.Group("/user")
{
userRouter.Use(middleware.Cost()) // 为当前分组使用计算耗时中间件
userRouter.Get("/login", DefaultHandler)
userRouter.Get("/logout", DefaultHandler)
}
server := &http.Server{
Handler: core,
Addr: ":80",
}
// 启动 http 服务
go func() {
server.ListenAndServe()
}()
quit := make(chan os.Signal, 1)
// ctrl+c : SIGINT
// ctrl+\ : SIGQUIT
// kill : SIGTERM
// kill -9 : SIGKILL // 不能被捕获
signal.Notify(quit, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
<-quit
fmt.Println("shutdown...")
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
<-ticker.C
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(timeoutCtx); err != nil {
log.Fatal("server shutdown: ", err)
}
}