-
Notifications
You must be signed in to change notification settings - Fork 14
/
gin_server.go
68 lines (55 loc) · 1.32 KB
/
gin_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
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/gin-gonic/gin"
"github.com/lesismal/nbio/nbhttp"
"github.com/lesismal/nbio/nbhttp/websocket"
)
var upgrader = websocket.NewUpgrader()
func init() {
upgrader.OnMessage(func(c *websocket.Conn, messageType websocket.MessageType, data []byte) {
// echo
c.WriteMessage(messageType, data)
})
upgrader.OnClose(func(c *websocket.Conn, err error) {
log.Println("OnClose:", c.RemoteAddr().String(), err)
})
}
func onHello(c *gin.Context) {
c.String(http.StatusOK, "hello world")
}
func onWebsocket(c *gin.Context) {
w := c.Writer
r := c.Request
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
panic(err)
}
log.Println("OnOpen:", conn.RemoteAddr().String())
}
func main() {
router := gin.New()
router.GET("/hello", onHello)
router.GET("/ws", onWebsocket)
engine := nbhttp.NewEngine(nbhttp.Config{
Network: "tcp",
Addrs: []string{"localhost:8080"},
Handler: router,
})
err := engine.Start()
if err != nil {
log.Fatalf("nbio.Start failed: %v\n", err)
}
log.Println("serving [gin-gonic/gin] on [nbio]")
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
<-interrupt
ctx, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
engine.Shutdown(ctx)
}