Commit 312b4338 authored by Artemis's avatar Artemis 🐱

Setting CORS headers on POST route

parent e80b843d
......@@ -9,6 +9,7 @@ import (
"time"
)
// region Data Structures
type Handlers struct {
BackendService *storage.BackendService
Templates *template.Template
......@@ -20,11 +21,14 @@ type Content struct {
Raw string
}
// endregion
// region Router
func (h Handlers) GetRouter() *vestigo.Router {
r := vestigo.NewRouter()
r.Get("/", h.HandleHome)
r.Post("/", h.HandleNewPaste)
r.Post("/", h.HandleNewPaste, OpenCORSMiddleware)
r.Get("/about", h.HandleAbout)
r.Get("/s/:key", h.HandleShowPaste)
r.Get("/r/:key", h.HandleShowRaw)
......@@ -33,6 +37,26 @@ func (h Handlers) GetRouter() *vestigo.Router {
return r
}
// endregion
// region Middlewares
func OpenCORSMiddleware(f http.HandlerFunc) http.HandlerFunc {
// This middleware accepts requests from everywhere, on the OPTIONS, GET and POST method only.
return func(w http.ResponseWriter, r *http.Request) {
for key, value := range map[string]string{
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "OPTIONS, GET, POST",
} {
w.Header().Set(key, value)
}
f(w, r)
}
}
// endregion
// region Static pages
func (h Handlers) HandleHome(w http.ResponseWriter, req *http.Request) {
_ = h.Templates.ExecuteTemplate(w, "homepage", nil)
}
......@@ -41,6 +65,13 @@ func (h Handlers) HandleAbout(w http.ResponseWriter, req *http.Request) {
_ = h.Templates.ExecuteTemplate(w, "about", nil)
}
func (h Handlers) HandleStaticContent(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, "./static/"+vestigo.Param(req, "_name"))
}
// endregion
// region Paste ephemeral handling
func (h Handlers) HandleNewPaste(w http.ResponseWriter, req *http.Request) {
err := req.ParseForm()
......@@ -150,6 +181,4 @@ func (h Handlers) HandleShowRaw(w http.ResponseWriter, req *http.Request) {
_, _ = fmt.Fprint(w, res)
}
func (h Handlers) HandleStaticContent(w http.ResponseWriter, req *http.Request) {
http.ServeFile(w, req, "./static/"+vestigo.Param(req, "_name"))
}
// endregion
......@@ -4,10 +4,19 @@ import (
"github.com/go-redis/redis"
)
// region Base type
type RedisBackend struct {
Client *redis.Client
}
func (r *RedisBackend) Init(opts *redis.Options) error {
r.Client = redis.NewClient(opts)
res := r.Client.Ping()
return res.Err()
}
// endregion
// region Backend interface implementation
func (r *RedisBackend) Persist(key string, value string, options *PersistOptions) error {
return r.Client.
Set(key, value, options.Expiration).
......@@ -30,9 +39,4 @@ func (r *RedisBackend) Retrieve(key string) (string, error) {
// Found
return res.Val(), nil
}
func (r *RedisBackend) Init(opts *redis.Options) error {
r.Client = redis.NewClient(opts)
res := r.Client.Ping()
return res.Err()
}
// endregion
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment