-
Notifications
You must be signed in to change notification settings - Fork 19
/
main.go
111 lines (92 loc) · 2.15 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"golang.org/x/time/rate"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"github.com/pallat/todoapi/todo"
)
var (
buildcommit = "dev"
buildtime = time.Now().String()
)
func main() {
err = godotenv.Load("local.env")
if err != nil {
log.Printf("please consider environment variables: %s\n", err)
}
db, err := gorm.Open(sqlite.Open(os.Getenv("DB_CONN")), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
if err :=db.AutoMigrate(&todo.Todo{});err != nil {
log.Println("auto migrate db",err)
}
r := gin.Default()
config := cors.DefaultConfig()
config.AllowOrigins = []string{
"http://localhost:8080",
}
config.AllowHeaders = []string{
"Origin",
"Authorization",
"TransactionID",
}
r.Use(cors.New(config))
r.GET("/healthz", func(c *gin.Context) {
c.Status(200)
})
r.GET("/limitz", limitedHandler)
r.GET("/x", func(c *gin.Context) {
c.JSON(200, gin.H{
"buildcommit": buildcommit,
"buildtime": buildtime,
})
})
handler := todo.NewTodoHandler(db)
r.POST("/todos", handler.NewTask)
r.GET("/todos", handler.List)
r.DELETE("/todos/:id", handler.Remove)
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
s := &http.Server{
Addr: ":" + os.Getenv("PORT"),
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go func() {
if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
<-ctx.Done()
stop()
fmt.Println("shutting down gracefully, press Ctrl+C again to force")
timeoutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := s.Shutdown(timeoutCtx); err != nil {
fmt.Println(err)
}
}
var limiter = rate.NewLimiter(5, 5)
func limitedHandler(c *gin.Context) {
if !limiter.Allow() {
c.AbortWithStatus(http.StatusTooManyRequests)
return
}
c.JSON(200, gin.H{
"message": "pong",
})
}