-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
83 lines (72 loc) · 1.71 KB
/
Copy pathmain.go
File metadata and controls
83 lines (72 loc) · 1.71 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
package main
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
// shutdown functions
shutdownFunctions := make([]func(context.Context), 0)
// signal
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(interrupt)
// errgroup
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
r := gin.Default()
server := &http.Server{Addr: ":8080", Handler: r}
shutdownFunctions = append(shutdownFunctions, func(ctx context.Context) {
err := server.Close()
if err != nil {
fmt.Println("failed to close http server!")
} else {
fmt.Println("succeed to close http server!")
}
})
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
}).
GET("/", func(c *gin.Context) {
_, err := c.Writer.Write([]byte("hello!\n"))
if err != nil {
fmt.Printf("error: %v\n", err.Error())
}
//c.String(http.StatusOK, "", "hello!\n")
})
err := server.ListenAndServe()
return err
})
//http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
// _, err := writer.Write([]byte("hello!\n"))
// if err != nil {
// fmt.Printf("write error: %v \n", err.Error())
// }
//})
//err := http.ListenAndServe(":8080", nil)
select {
case <-ctx.Done():
break
case <-interrupt:
break
}
timeout, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelFunc()
for _, shutdown := range shutdownFunctions {
shutdown(timeout)
}
err := g.Wait()
if err != nil {
panic(err)
}
}