-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
157 lines (138 loc) · 4.03 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package main
import (
"compress/gzip"
"flag"
"fmt"
"html/template"
"log"
"net/http"
"net/url"
"sync"
"time"
mw "gosh/middleware"
"gosh/router"
)
func main() {
zip := flag.Bool("zip", false, "set this flag to compress static files ahead of time")
dsName := flag.String("ds", ":memory:", "name of the datasource to use for SQLite3 database")
addr := flag.String("addr", "0.0.0.0:1234", "TCP address to use for the servers")
flag.Parse()
db, err := MakeDBService(*dsName)
defer db.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("Connected to the database")
fs := FileServer(*zip)
log.Printf("Created a fileserver (compressed static files = %v)", *zip)
stats := LinksStats{}
go LinksStatsUpdater(log.Default(), &db, &stats)
mux := router.NewRouterMux()
mux.Get("/static/**", mw.Logging(log.Default(), mw.NoTrailingSlash(http.StripPrefix("/static/", fs))))
mux.Get("/", mw.Logging(log.Default(), mw.Gzip(gzip.DefaultCompression, IndexPageHandler(&db, &stats))))
mux.Post("/", mw.Logging(log.Default(), mw.Gzip(gzip.DefaultCompression, CreateLinkHandler(&db, &stats))))
mux.Get("/*", mw.Logging(log.Default(), RedirectHandler(&db, mux.NotFound)))
log.Printf("Started server at address '%s'", *addr)
http.ListenAndServe(*addr, &mux)
}
const StaticFilesPath = "./static"
const StaticZippedFilesPath = "./static-zipped"
func FileServer(zip bool) http.Handler {
if zip {
fs, err := ZippedFileServer(StaticFilesPath, StaticZippedFilesPath)
if err != nil {
log.Fatal(err)
}
return fs
}
return mw.Gzip(gzip.DefaultCompression, http.FileServer(http.Dir(StaticFilesPath)))
}
func IndexPageHandler(db *DBService, stats *LinksStats) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := indexTemplate(w, nil, stats); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func CreateLinkHandler(db *DBService, stats *LinksStats) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
http.Error(w, "Couldn't parse sent form", http.StatusBadRequest)
return
}
clientUrl := r.FormValue("url")
if parsed, err := url.Parse(clientUrl); err != nil || parsed.Host == "" {
serr := fmt.Sprintf("'%s' is not a valid absolute URL", clientUrl)
http.Error(w, serr, http.StatusBadRequest)
return
}
slug, err := db.CreateShortenedUrl(clientUrl)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
created := CreatedLink {
Slug: slug,
Full: clientUrl,
Host: r.Host,
}
if err := indexTemplate(w, &created, stats); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
func RedirectHandler(db *DBService, notFoundHandler http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
slug := router.PathPart(r.URL, 0)
fullUrl, err, exists := db.GetUrl(slug)
if !exists {
notFoundHandler.ServeHTTP(w, r)
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, fullUrl, http.StatusSeeOther)
}
}
type CreatedLink struct {
Slug, Full, Host string
}
type LinksStats struct {
mu sync.Mutex
UrlsCount, RedirectsCount int
}
func indexTemplate(w http.ResponseWriter, created *CreatedLink, stats *LinksStats) error {
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
return err
}
var tmplData struct {
Created *CreatedLink
Stats *LinksStats
}
tmplData.Created = created
stats.mu.Lock()
defer stats.mu.Unlock()
tmplData.Stats = stats
return tmpl.Execute(w, &tmplData)
}
const UpdaterInterval = 60 * time.Second
func LinksStatsUpdater(logger *log.Logger, db *DBService, stats *LinksStats) {
for {
visits, err := db.TotalVisits()
if err != nil {
logger.Printf("Updater error %v", err)
}
urls, err := db.TotalUrls()
if err != nil {
logger.Printf("Updater error %v", err)
}
stats.mu.Lock()
stats.UrlsCount = urls
stats.RedirectsCount = visits
stats.mu.Unlock()
time.Sleep(UpdaterInterval)
}
}