qurl/pages/root.go

94 lines
2.0 KiB
Go
Raw Normal View History

package pages
import (
"fmt"
"html/template"
"net/http"
"git.binarythought.com/cdramey/qurl/static"
"git.binarythought.com/cdramey/qurl/storage"
"git.binarythought.com/cdramey/qurl/obj"
)
type RootHandler struct {
Storage storage.Storage
index *StaticContent
css *StaticContent
favi *StaticContent
usage *StaticContent
submit *template.Template
}
func (ctx *RootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fname := r.URL.Path
switch fname {
case "/index.html":
fallthrough
case "/":
ctx.index.ServeHTTP(w, r)
case "/submit.html":
ctx.ServeSubmit(w, r)
case "/qurl.css":
ctx.css.ServeHTTP(w, r)
case "/favicon.ico":
ctx.favi.ServeHTTP(w, r)
2018-11-23 19:18:26 -09:00
case "/api/usage.html":
ctx.usage.ServeHTTP(w, r)
2018-11-19 07:03:33 -09:00
case "/api/url":
ctx.ServeAPI(w, r)
default:
id, err := obj.FromString(fname[1:len(fname)])
if err != nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
2018-11-23 19:22:41 -09:00
return
}
q, err := ctx.Storage.GetQURLByID(id)
if err != nil {
http.Error(w, fmt.Sprintf("Database error: %s", err.Error()),
http.StatusInternalServerError)
return
}
2018-11-23 19:22:41 -09:00
if q == nil {
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
http.Redirect(w, r, q.URL, http.StatusPermanentRedirect)
}
}
func (ctx *RootHandler) Init() error {
// Initialize the static content object for the index page
ctx.index = &StaticContent{Type: "text/html", Content: static.Index_html}
ctx.index.Init()
// Initialize the static content object for the css
ctx.css = &StaticContent{Type: "text/css", Content: static.Qurl_css}
ctx.css.Init()
2018-11-23 19:18:26 -09:00
// Initialize the static content object favicon
ctx.favi = &StaticContent{Type: "image/x-icon", Content: static.Favicon_ico}
ctx.favi.Init()
2018-11-23 19:18:26 -09:00
// Initialize the api usage instructions
ctx.usage = &StaticContent{Type: "text/html", Content: static.Usage_html}
ctx.usage.Init()
2018-11-23 19:18:26 -09:00
// Initialize submit page template
ctx.submit = template.New("submit.html")
_, err := ctx.submit.Parse(string(static.Submit_html))
if err != nil {
return err
}
return nil
}