-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
96 lines (74 loc) · 1.59 KB
/
main.go
File metadata and controls
96 lines (74 loc) · 1.59 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
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"context"
"database/sql"
"embed"
"errors"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/go-chi/chi/v5"
_ "github.com/mattn/go-sqlite3"
)
//go:embed assets/*
var assets embed.FS
type App struct {
db *sql.DB
}
func main() {
db, err := sql.Open("sqlite3", "paste.db")
if err != nil {
panic(err)
}
_, err = db.Exec("PRAGMA journal_mode=WAL")
if err != nil {
panic(err)
}
query := `CREATE TABLE IF NOT EXISTS pastes(
id TEXT PRIMARY KEY,
created_at INTEGER NOT NULL,
country_code TEXT NOT NULL,
views INTEGER NOT NULL DEFAULT 0,
last_view INTEGER DEFAULT NULL,
content BLOB NOT NULL
) STRICT`
_, err = db.Exec(query)
if err != nil {
panic(err)
}
app := &App{
db: db,
}
router := chi.NewRouter()
router.Use(app.RealIP)
router.Use(app.RateLimit)
router.Use(app.LogRequest)
router.Get("/", app.GetIndex)
router.Post("/save", app.PostSave())
router.Get("/{id:[A-Za-z0-9]{8}}", app.GetPaste)
router.Get("/raw/{id:[A-Za-z0-9]{8}}", app.GetRawPaste)
router.Get("/*", app.ServeAssets)
router.NotFound(app.NotFound)
router.MethodNotAllowed(app.MethodNotAllowed)
server := &http.Server{
Addr: ":80",
Handler: router,
ReadTimeout: 5 * time.Minute,
WriteTimeout: 5 * time.Minute,
}
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
panic(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Println(err)
}
}