package main import ( "fmt" "html/template" "log" "net/http" "os" "regexp" "strconv" "strings" "time" "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 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", } var base_template = template.Must(template.ParseFiles( "views/base.html", "views/header.html", "views/footer.html", "views/prideflag.html", )) var htmx_template = template.Must(template.New("root").Parse(`{{block "head" .}}{{end}}{{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) } 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 } } 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()) } if req.URL.Path == "/" { return index_handler(writer, root) } if uri == "/music" || uri == "/music/" { return music_directory_handler(writer, root) } if strings.HasPrefix(uri, "/music/") { return music_gateway_handler(writer, req, root) } return static_handler(writer, req) }(writer, req) log_request(req, code, start_time) } func index_handler(writer http.ResponseWriter, root *template.Template) int { 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 music_directory_handler(writer http.ResponseWriter, root *template.Template) int { 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 music_gateway_handler(writer http.ResponseWriter, req *http.Request, root *template.Template) int { id := req.URL.Path[len("/music/"):] // http.Redirect(writer, req, "https://mellodoot.com/music/"+title, 302) // return release, ok := music.GetRelease(id) if !ok { http.Error(writer, "404 not found", http.StatusNotFound) return 404 } 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 static_handler(writer http.ResponseWriter, req *http.Request) int { filename := "public/" + req.URL.Path[1:] // check the file's metadata info, err := os.Stat(filename) if err != nil { http.Error(writer, "404 not found", http.StatusNotFound) return 404 } if len(req.Header["If-Modified-Since"]) > 0 && req.Header["If-Modified-Since"][0] != "" { if_modified_since_time, err := time.Parse(http.TimeFormat, req.Header["If-Modified-Since"][0]) if err != nil { http.Error(writer, "400 bad request", http.StatusBadRequest) return 400 } if req.Header["If-Modified-Since"][0] == info.ModTime().Format(http.TimeFormat) || if_modified_since_time.After(info.ModTime()) { writer.WriteHeader(304) // not modified return 304 } } // set other nice headers writer.Header().Set("Cache-Control", "max-age=86400") writer.Header().Set("Last-Modified", info.ModTime().Format(http.TimeFormat)) // Last-Modified: , :: GMT // Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT // 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 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 main() { push_to_db_this_is_a_testing_thing_and_will_be_superfluous_later() http.HandleFunc("/", handle_request) fmt.Printf("now serving at http://127.0.0.1:%d\n", PORT) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", PORT), nil)) }