-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
84 lines (68 loc) · 2.6 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
package main
import (
"context"
"fmt"
"net/http"
"time"
"github.com/wavly/shawty/asserts"
"github.com/wavly/shawty/config"
"github.com/wavly/shawty/env"
"github.com/wavly/shawty/handlers"
"github.com/wavly/shawty/internal/database"
prettylogger "github.com/wavly/shawty/pretty-logger"
"github.com/wavly/shawty/utils"
)
func main() {
router := http.NewServeMux()
logger := prettylogger.GetLogger(nil)
// Get the env variables and other config options
config.Init()
// Create the URLs table in the database
db := utils.ConnectDB()
err := database.New(db).CreateUrlTable(context.Background())
asserts.NoErr(err, "Failed to creating the URLs table in the database")
db.Close()
// Serving static files with caching
router.Handle("GET /static/", http.StripPrefix("/static/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set Cache-Control headers for 10 days
w.Header().Set("Cache-Control", "public, max-age=864000")
// Set Last-Modified header
w.Header().Set("Last-Modified", time.Now().UTC().Format(http.TimeFormat))
// Serve the static content
http.FileServer(http.Dir("./static")).ServeHTTP(w, r)
logger.Debug("Request for static content", "resource", r.URL.Path, "user-agent", r.UserAgent())
})))
// Route for index page
router.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
logger.Warn("Page not found", "route", r.URL.Path, "user-agent", r.UserAgent())
// NOTE: HTMX doesn't swap the elements if the returned status code isn't successful, e.g 4xx, 5xx
// This is fine "here" because it isn't using the hx-trigger attribute to swap the elements
w.WriteHeader(http.StatusNotFound)
utils.Templ("./templs/404.html").Execute(w, nil)
return
}
w.Write(utils.StaticFile("./static/index.html"))
})
// Route for stats page
router.HandleFunc("GET /stat/{code}", handlers.Stats)
// Route to handle redirection
router.HandleFunc("GET /s/{code}", handlers.Redirect)
// Route for unshortening the URL
router.HandleFunc("GET /unshort", func(w http.ResponseWriter, r *http.Request) {
w.Write(utils.StaticFile("./static/unshort.html"))
})
// API route for shortening the URL
router.HandleFunc("POST /shawty", handlers.Shawty)
// API route for unshortening the URL
router.HandleFunc("POST /unshort", handlers.Unshort)
fmt.Printf("Listening on: %s\n\n", env.PORT)
server := &http.Server{
Addr: ":" + env.PORT,
Handler: router,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 15 * time.Second,
}
asserts.NoErr(server.ListenAndServe(), "Failed to start the server")
}