added stuff, broke some other stuff, made admin auth!
Signed-off-by: ari melody <ari@arimelody.me>
This commit is contained in:
parent
0d1e694b59
commit
5631c4bd87
26 changed files with 1615 additions and 1401 deletions
446
main.go
446
main.go
|
@ -5,278 +5,212 @@ import (
|
|||
"html/template"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"arimelody.me/arimelody.me/api"
|
||||
"arimelody.me/arimelody.me/api/v1/admin"
|
||||
"arimelody.me/arimelody.me/api/v1/music"
|
||||
|
||||
"github.com/gomarkdown/markdown"
|
||||
"github.com/gomarkdown/markdown/html"
|
||||
"github.com/gomarkdown/markdown/parser"
|
||||
)
|
||||
|
||||
const PORT int = 8080
|
||||
var LAST_MODIFIED = time.Now()
|
||||
|
||||
var mime_types = map[string]string{
|
||||
"css": "text/css; charset=utf-8",
|
||||
"png": "image/png",
|
||||
"jpg": "image/jpg",
|
||||
"webp": "image/webp",
|
||||
"html": "text/html",
|
||||
"asc": "text/plain",
|
||||
"pub": "text/plain",
|
||||
"js": "application/javascript",
|
||||
}
|
||||
const DEFAULT_PORT int = 8080
|
||||
|
||||
var base_template = template.Must(template.ParseFiles(
|
||||
"views/base.html",
|
||||
"views/header.html",
|
||||
"views/footer.html",
|
||||
"views/prideflag.html",
|
||||
"views/base.html",
|
||||
"views/header.html",
|
||||
"views/footer.html",
|
||||
"views/prideflag.html",
|
||||
))
|
||||
// var htmx_template = template.Must(template.New("root").Parse(`<head>{{block "head" .}}{{end}}</head>{{block "content" .}}{{end}}`))
|
||||
|
||||
func log_request(req *http.Request, code int, start_time time.Time) {
|
||||
now := time.Now()
|
||||
difference := (now.Nanosecond() - start_time.Nanosecond()) / 1_000_000
|
||||
elapsed := "<1"
|
||||
if difference >= 1 {
|
||||
elapsed = strconv.Itoa(difference)
|
||||
}
|
||||
now := time.Now()
|
||||
difference := (now.Nanosecond() - start_time.Nanosecond()) / 1_000_000
|
||||
elapsed := "<1"
|
||||
if difference >= 1 {
|
||||
elapsed = strconv.Itoa(difference)
|
||||
}
|
||||
|
||||
fmt.Printf("[%s] %s %s - %d (%sms) (%s)\n",
|
||||
now.Format(time.UnixDate),
|
||||
req.Method,
|
||||
req.URL.Path,
|
||||
code,
|
||||
elapsed,
|
||||
req.Header["User-Agent"][0],
|
||||
)
|
||||
fmt.Printf("[%s] %s %s - %d (%sms) (%s)\n",
|
||||
now.Format(time.UnixDate),
|
||||
req.Method,
|
||||
req.URL.Path,
|
||||
code,
|
||||
elapsed,
|
||||
req.Header["User-Agent"][0])
|
||||
}
|
||||
|
||||
func handle_request(writer http.ResponseWriter, req *http.Request) {
|
||||
uri := req.URL.Path
|
||||
start_time := time.Now()
|
||||
|
||||
// hx_request := len(req.Header["Hx-Request"]) > 0 && req.Header["Hx-Request"][0] == "true"
|
||||
//
|
||||
// // don't bother fulfilling requests to a page that's already loaded on the client!
|
||||
// if hx_request && len(req.Header["Referer"]) > 0 && len(req.Header["Hx-Current-Url"]) > 0 {
|
||||
// regex := regexp.MustCompile(`https?:\/\/[^\/]+`)
|
||||
// current_location := regex.ReplaceAllString(req.Header["Hx-Current-Url"][0], "")
|
||||
// if current_location == req.URL.Path {
|
||||
// writer.WriteHeader(204);
|
||||
// return
|
||||
// }
|
||||
// }
|
||||
|
||||
writer.Header().Set("Server", "arimelody.me")
|
||||
writer.Header().Set("Cache-Control", "max-age=86400")
|
||||
writer.Header().Set("Last-Modified", LAST_MODIFIED.Format(http.TimeFormat))
|
||||
|
||||
code := func(writer http.ResponseWriter, req *http.Request) int {
|
||||
// var root *template.Template
|
||||
// if hx_request {
|
||||
// root = template.Must(htmx_template.Clone())
|
||||
// } else {
|
||||
// root = template.Must(base_template.Clone())
|
||||
// }
|
||||
|
||||
var root = template.Must(base_template.Clone())
|
||||
|
||||
if req.URL.Path == "/" {
|
||||
return handle_index(writer, req, root)
|
||||
}
|
||||
|
||||
if uri == "/music" || uri == "/music/" {
|
||||
return handle_music(writer, req, root)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(uri, "/music/") {
|
||||
return handle_music_gateway(writer, req, root)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(uri, "/admin") {
|
||||
return handle_admin(writer, req, root)
|
||||
}
|
||||
|
||||
if strings.HasPrefix(uri, "/api") {
|
||||
return api.Handle(writer, req, root)
|
||||
}
|
||||
|
||||
return static_handler(writer, req, root)
|
||||
}(writer, req)
|
||||
|
||||
log_request(req, code, start_time)
|
||||
}
|
||||
|
||||
func handle_index(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
if !was_modified(req, LAST_MODIFIED) {
|
||||
writer.WriteHeader(304)
|
||||
return 304
|
||||
}
|
||||
|
||||
index_template := template.Must(root.ParseFiles("views/index.html"))
|
||||
err := index_template.Execute(writer, nil)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
return 200
|
||||
}
|
||||
|
||||
func handle_music(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
if !was_modified(req, LAST_MODIFIED) {
|
||||
writer.WriteHeader(304)
|
||||
return 304
|
||||
}
|
||||
|
||||
music_template := template.Must(root.ParseFiles("views/music.html"))
|
||||
music := music.QueryAllMusic()
|
||||
err := music_template.Execute(writer, music)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
return 200
|
||||
}
|
||||
|
||||
func handle_music_gateway(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
if !was_modified(req, LAST_MODIFIED) {
|
||||
writer.WriteHeader(304)
|
||||
return 304
|
||||
}
|
||||
|
||||
id := req.URL.Path[len("/music/"):]
|
||||
// http.Redirect(writer, req, "https://mellodoot.com/music/"+title, 302)
|
||||
// return
|
||||
release, ok := music.GetRelease(id)
|
||||
if !ok {
|
||||
return handle_not_found(writer, req, root)
|
||||
}
|
||||
gateway_template := template.Must(root.ParseFiles("views/music-gateway.html"))
|
||||
err := gateway_template.Execute(writer, release)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
return 200
|
||||
}
|
||||
|
||||
func handle_admin(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
if !was_modified(req, LAST_MODIFIED) {
|
||||
writer.WriteHeader(304)
|
||||
return 304
|
||||
}
|
||||
|
||||
admin_template := template.Must(root.ParseFiles("views/admin.html"))
|
||||
err := admin_template.Execute(writer, nil)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
return 200
|
||||
}
|
||||
|
||||
func static_handler(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
filename := "public/" + req.URL.Path[1:]
|
||||
|
||||
// check the file's metadata
|
||||
info, err := os.Stat(filename)
|
||||
if err != nil {
|
||||
return handle_not_found(writer, req, root)
|
||||
}
|
||||
|
||||
if !was_modified(req, info.ModTime()) {
|
||||
writer.WriteHeader(304)
|
||||
return 304
|
||||
}
|
||||
|
||||
// set Last-Modified to file modification date
|
||||
writer.Header().Set("Last-Modified", info.ModTime().Format(http.TimeFormat))
|
||||
|
||||
// read the file
|
||||
body, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
|
||||
// setting MIME types
|
||||
filetype := filename[strings.LastIndex(filename, ".")+1:]
|
||||
if mime_type, ok := mime_types[filetype]; ok {
|
||||
writer.Header().Set("Content-Type", mime_type)
|
||||
} else {
|
||||
writer.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
}
|
||||
|
||||
writer.Write([]byte(body))
|
||||
return 200
|
||||
}
|
||||
|
||||
func handle_not_found(writer http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
type ErrorData struct {
|
||||
Target string
|
||||
}
|
||||
error_data := ErrorData{ Target: req.URL.Path }
|
||||
writer.WriteHeader(404);
|
||||
error_template := template.Must(root.ParseFiles("views/404.html"))
|
||||
err := error_template.Execute(writer, error_data)
|
||||
if err != nil {
|
||||
http.Error(writer, err.Error(), http.StatusInternalServerError)
|
||||
return 500
|
||||
}
|
||||
return 404
|
||||
}
|
||||
|
||||
func was_modified(req *http.Request, last_modified time.Time) bool {
|
||||
if len(req.Header["If-Modified-Since"]) == 0 || len(req.Header["If-Modified-Since"][0]) == 0 {
|
||||
return true
|
||||
}
|
||||
request_time, err := time.Parse(http.TimeFormat, req.Header["If-Modified-Since"][0])
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
if request_time.Before(last_modified) {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parse_markdown(md []byte) []byte {
|
||||
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
|
||||
p := parser.NewWithExtensions(extensions)
|
||||
doc := p.Parse(md)
|
||||
|
||||
htmlFlags := html.CommonFlags
|
||||
opts := html.RendererOptions{Flags: htmlFlags}
|
||||
renderer := html.NewRenderer(opts)
|
||||
|
||||
return markdown.Render(doc, renderer)
|
||||
}
|
||||
|
||||
func push_to_db_this_is_a_testing_thing_and_will_be_superfluous_later() {
|
||||
db := InitDatabase()
|
||||
defer db.Close()
|
||||
|
||||
for _, artist := range music.QueryAllArtists() {
|
||||
PushArtist(db, artist)
|
||||
}
|
||||
|
||||
for _, album := range music.QueryAllMusic() {
|
||||
PushRelease(db, album)
|
||||
}
|
||||
}
|
||||
// func handle_request(res http.ResponseWriter, req *http.Request) {
|
||||
// uri := req.URL.Path
|
||||
// start_time := time.Now()
|
||||
//
|
||||
// res.Header().Set("Server", "arimelody.me")
|
||||
//
|
||||
// code := func(res http.ResponseWriter, req *http.Request) int {
|
||||
// var root = template.Must(base_template.Clone())
|
||||
//
|
||||
// if req.URL.Path == "/" {
|
||||
// return handle_index(res, req, root)
|
||||
// }
|
||||
//
|
||||
// if uri == "/music" || uri == "/music/" {
|
||||
// return handle_music(res, req, root)
|
||||
// }
|
||||
//
|
||||
// if strings.HasPrefix(uri, "/music/") {
|
||||
// return handle_music_gateway(res, req, root)
|
||||
// }
|
||||
//
|
||||
// if strings.HasPrefix(uri, "/admin") {
|
||||
// return admin.Handle(res, req, root)
|
||||
// }
|
||||
//
|
||||
// if strings.HasPrefix(uri, "/api") {
|
||||
// return api.Handle(res, req, root)
|
||||
// }
|
||||
//
|
||||
// return static_handler(res, req, root)
|
||||
// }(res, req)
|
||||
//
|
||||
// log_request(req, code, start_time)
|
||||
// }
|
||||
//
|
||||
// func handle_index(res http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
// if !global.IsModified(req, global.LAST_MODIFIED) {
|
||||
// res.WriteHeader(304)
|
||||
// return 304
|
||||
// }
|
||||
//
|
||||
// index_template := template.Must(root.ParseFiles("views/index.html"))
|
||||
// err := index_template.Execute(res, nil)
|
||||
// if err != nil {
|
||||
// http.Error(res, err.Error(), http.StatusInternalServerError)
|
||||
// return 500
|
||||
// }
|
||||
// return 200
|
||||
// }
|
||||
//
|
||||
// func handle_music(res http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
// if !global.IsModified(req, global.LAST_MODIFIED) {
|
||||
// res.WriteHeader(304)
|
||||
// return 304
|
||||
// }
|
||||
//
|
||||
// music_template := template.Must(root.ParseFiles("views/music.html"))
|
||||
// err := music_template.Execute(res, music.Releases)
|
||||
// if err != nil {
|
||||
// http.Error(res, err.Error(), http.StatusInternalServerError)
|
||||
// return 500
|
||||
// }
|
||||
// return 200
|
||||
// }
|
||||
//
|
||||
// func handle_music_gateway(res http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
// if !global.IsModified(req, global.LAST_MODIFIED) {
|
||||
// res.WriteHeader(304)
|
||||
// return 304
|
||||
// }
|
||||
//
|
||||
// id := req.URL.Path[len("/music/"):]
|
||||
// release, err := music.GetRelease(id)
|
||||
// if err != nil {
|
||||
// return handle_not_found(res, req, root)
|
||||
// }
|
||||
// gateway_template := template.Must(root.ParseFiles("views/music-gateway.html"))
|
||||
// err = gateway_template.Execute(res, release)
|
||||
// if err != nil {
|
||||
// http.Error(res, err.Error(), http.StatusInternalServerError)
|
||||
// return 500
|
||||
// }
|
||||
// return 200
|
||||
// }
|
||||
//
|
||||
// func static_handler(res http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
// filename := "public/" + req.URL.Path[1:]
|
||||
//
|
||||
// // check the file's metadata
|
||||
// info, err := os.Stat(filename)
|
||||
// if err != nil {
|
||||
// return handle_not_found(res, req, root)
|
||||
// }
|
||||
//
|
||||
// if !global.IsModified(req, info.ModTime()) {
|
||||
// res.WriteHeader(304)
|
||||
// return 304
|
||||
// }
|
||||
//
|
||||
// // set Last-Modified to file modification date
|
||||
// res.Header().Set("Last-Modified", info.ModTime().Format(http.TimeFormat))
|
||||
//
|
||||
// // read the file
|
||||
// body, err := os.ReadFile(filename)
|
||||
// if err != nil {
|
||||
// http.Error(res, err.Error(), http.StatusInternalServerError)
|
||||
// return 500
|
||||
// }
|
||||
//
|
||||
// // setting MIME types
|
||||
// filetype := filename[strings.LastIndex(filename, ".")+1:]
|
||||
// if mime_type, ok := global.MimeTypes[filetype]; ok {
|
||||
// res.Header().Set("Content-Type", mime_type)
|
||||
// } else {
|
||||
// res.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
// }
|
||||
//
|
||||
// res.Write([]byte(body))
|
||||
// return 200
|
||||
// }
|
||||
//
|
||||
// func handle_not_found(res http.ResponseWriter, req *http.Request, root *template.Template) int {
|
||||
// type ErrorData struct {
|
||||
// Target string
|
||||
// }
|
||||
// error_data := ErrorData{ Target: req.URL.Path }
|
||||
// res.WriteHeader(404);
|
||||
// error_template := template.Must(root.ParseFiles("views/404.html"))
|
||||
// err := error_template.Execute(res, error_data)
|
||||
// if err != nil {
|
||||
// http.Error(res, err.Error(), http.StatusInternalServerError)
|
||||
// return 500
|
||||
// }
|
||||
// return 404
|
||||
// }
|
||||
//
|
||||
// func parse_markdown(md []byte) []byte {
|
||||
// extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
|
||||
// p := parser.NewWithExtensions(extensions)
|
||||
// doc := p.Parse(md)
|
||||
//
|
||||
// htmlFlags := html.CommonFlags
|
||||
// opts := html.RendererOptions{Flags: htmlFlags}
|
||||
// renderer := html.NewRenderer(opts)
|
||||
//
|
||||
// return markdown.Render(doc, renderer)
|
||||
// }
|
||||
|
||||
func main() {
|
||||
push_to_db_this_is_a_testing_thing_and_will_be_superfluous_later()
|
||||
db := InitDatabase()
|
||||
defer db.Close()
|
||||
|
||||
var err error
|
||||
music.Artists, err = PullAllArtists(db)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to pull artists from database: %v\n", err);
|
||||
panic(1)
|
||||
}
|
||||
music.Releases, err = PullAllReleases(db)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to pull releases from database: %v\n", err);
|
||||
panic(1)
|
||||
}
|
||||
|
||||
http.HandleFunc("/", handle_request)
|
||||
mux := http.NewServeMux()
|
||||
|
||||
fmt.Printf("now serving at http://127.0.0.1:%d\n", PORT)
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil))
|
||||
mux.Handle("/api/v1/admin", admin.Handler())
|
||||
mux.Handle("/api/v1/admin/login", admin.LoginHandler())
|
||||
mux.Handle("/api/v1/admin/callback", admin.OAuthCallbackHandler())
|
||||
mux.Handle("/api/v1/admin/verify", admin.AuthorisedHandler(admin.VerifyHandler()))
|
||||
mux.Handle("/api/v1/admin/logout", admin.AuthorisedHandler(admin.LogoutHandler()))
|
||||
|
||||
port := DEFAULT_PORT
|
||||
fmt.Printf("now serving at http://127.0.0.1:%d\n", port)
|
||||
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), mux))
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue