-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweb.go
156 lines (137 loc) · 4.05 KB
/
web.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 (
"embed"
"encoding/json"
"errors"
"fmt"
"io/fs"
"log"
"net/http"
"regexp"
"strings"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttpadaptor"
"github.com/xtrafrancyz/golish/backend"
)
//go:embed admin/*
var adminFiles embed.FS
type web struct {
backend backend.Backend
}
func (w *web) run() {
r := router.New()
r.GET("/", w.handleRoot)
r.GET("/{slug:["+Config.slugCharacters+"]+}", w.handleSlug)
adminGroup := r.Group("/@" + Config.adminPath)
adminGroup.GET("/list", w.handleList)
adminGroup.POST("/create", w.handleCreate)
adminGroup.POST("/delete", w.handleDelete)
adminGroup.POST("/edit", w.handleEdit)
files, _ := fs.Sub(adminFiles, "admin")
adminGroup.GET("/{file:*}", fasthttpadaptor.NewFastHTTPHandler(
http.StripPrefix("/@"+Config.adminPath, http.FileServer(http.FS(files))),
))
server := &fasthttp.Server{
Handler: r.Handler,
ReduceMemoryUsage: true,
}
log.Printf("Starting server on http://%s:%d", Config.host, Config.port)
err := server.ListenAndServe(fmt.Sprintf("%s:%d", Config.host, Config.port))
if err != nil {
log.Fatalf("error in fasthttp server: %s", err)
}
}
func (w *web) handleRoot(ctx *fasthttp.RequestCtx) {
if Config.defaultRedirect != "" {
ctx.Redirect(Config.defaultRedirect, fasthttp.StatusFound)
} else {
ctx.NotFound()
}
}
func (w *web) handleSlug(ctx *fasthttp.RequestCtx) {
// Make a copy of a slug. fasthttp/router's UserValues become invalid after the request is completed.
slug := strings.Clone(ctx.UserValue("slug").(string))
full := w.backend.TryClickLink(slug)
if full != nil {
ctx.Redirect(full.Url, fasthttp.StatusFound)
} else {
ctx.NotFound()
}
}
func (w *web) handleAdminRoot(ctx *fasthttp.RequestCtx) {
path := "/" + ctx.UserValue("file").(string)
if path == "//" {
path = "/index.html"
}
bytes, err := adminFiles.ReadFile(path)
if err != nil {
ctx.NotFound()
} else {
if strings.HasSuffix(path, ".html") {
ctx.Response.Header.Set("Content-Type", "text/html")
} else if strings.HasSuffix(path, ".css") {
ctx.Response.Header.Set("Content-Type", "text/css")
} else if strings.HasSuffix(path, ".js") {
ctx.Response.Header.Set("Content-Type", "application/javascript")
} else if strings.HasSuffix(path, ".png") {
ctx.Response.Header.Set("Content-Type", "image/png")
}
ctx.SetStatusCode(fasthttp.StatusOK)
_, _ = ctx.Write(bytes)
}
}
func (w *web) handleList(ctx *fasthttp.RequestCtx) {
links := w.backend.GetAllLinks()
marshaled, _ := json.Marshal(links)
ctx.Response.Header.Set("Content-Type", "application/json")
_, _ = ctx.Write(marshaled)
}
func (w *web) handleCreate(ctx *fasthttp.RequestCtx) {
url := ctx.PostArgs().Peek("url")
slug := ctx.PostArgs().Peek("slug")
log.Printf("{admin}/create (url=%s, slug=%s)", url, slug)
if len(url) == 0 {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
} else {
var link *backend.Link = nil
var err error = nil
if len(slug) == 0 {
link, err = w.backend.Create(string(url))
} else {
if ok, _ := regexp.Match("^["+Config.slugCharacters+"]+$", slug); !ok {
err = errors.New("slug contains illegal characters")
} else {
link, err = w.backend.CreateCustom(string(slug), string(url))
}
}
var marshaled []byte
if err != nil {
marshaled, _ = json.Marshal(OperationError{
Error: true,
Message: err.Error(),
})
} else {
marshaled, _ = json.Marshal(link)
}
ctx.Response.Header.Set("Content-Type", "application/json")
_, _ = ctx.Write(marshaled)
}
}
func (w *web) handleDelete(ctx *fasthttp.RequestCtx) {
slug := ctx.PostArgs().Peek("slug")
log.Printf("{admin}/delete (slug=%s)", slug)
w.backend.Delete(string(slug))
ctx.SetStatusCode(fasthttp.StatusOK)
}
func (w *web) handleEdit(ctx *fasthttp.RequestCtx) {
slug := ctx.PostArgs().Peek("slug")
url := ctx.PostArgs().Peek("url")
log.Printf("{admin}/edit (slug=%s, url=%s)", slug, url)
w.backend.Edit(string(slug), string(url))
ctx.SetStatusCode(fasthttp.StatusOK)
}
type OperationError struct {
Error bool `json:"error"`
Message string `json:"message"`
}