roulette/cmd/web.go

102 lines
1.7 KiB
Go
Raw Normal View History

2022-09-08 15:12:06 +00:00
/*
Copyright © 2022 Seednode <seednode@seedno.de>
*/
package cmd
import (
"fmt"
"io"
"log"
"net/http"
2022-09-08 20:30:51 +00:00
"net/url"
2022-09-08 15:57:59 +00:00
"os"
2022-09-08 15:12:06 +00:00
"strconv"
)
2022-09-08 20:30:51 +00:00
func generateHeader(fileName string) string {
htmlHeader := `<html lang="en">
2022-09-08 15:12:06 +00:00
<head>
2022-09-08 20:30:51 +00:00
<style>img{max-width:100%;max-height:97vh;height:auto;}</style>
<title>`
htmlHeader += fileName
htmlHeader += `</title>
2022-09-08 15:12:06 +00:00
</head>
<body>
`
return htmlHeader
}
func generateFooter() string {
htmlFooter := ` </body>
</html>`
return htmlFooter
}
2022-09-08 20:30:51 +00:00
func generatePageHtml(w http.ResponseWriter, paths []string, output []string) {
fileList, err := getFileList(paths)
2022-09-08 15:12:06 +00:00
if err != nil {
2022-09-08 20:30:51 +00:00
panic(err)
2022-09-08 15:12:06 +00:00
}
2022-09-08 20:30:51 +00:00
fileName, filePath := pickFile(fileList)
2022-09-08 15:12:06 +00:00
w.Header().Add("Content-Type", "text/html")
2022-09-08 20:30:51 +00:00
_, err = io.WriteString(w, generateHeader(fileName))
2022-09-08 15:12:06 +00:00
if err != nil {
fmt.Println(err)
}
2022-09-08 20:30:51 +00:00
htmlBody := ` <a href="/"><img src="`
htmlBody += filePath
htmlBody += `"></img></a>
`
_, err = io.WriteString(w, htmlBody)
2022-09-08 15:12:06 +00:00
_, err = io.WriteString(w, generateFooter())
if err != nil {
fmt.Println(err)
}
}
2022-09-08 20:30:51 +00:00
func servePageHandler(paths []string) http.HandlerFunc {
2022-09-08 15:12:06 +00:00
return func(w http.ResponseWriter, r *http.Request) {
var output []string
2022-09-08 20:30:51 +00:00
request := r.RequestURI
if r.RequestURI == "/" {
generatePageHtml(w, paths, output)
} else {
f, err := url.QueryUnescape(request)
if err != nil {
log.Fatal(err)
return
}
buf, err := os.ReadFile(f)
if err != nil {
panic(err)
}
w.Write(buf)
}
2022-09-08 15:12:06 +00:00
}
}
func doNothing(http.ResponseWriter, *http.Request) {}
2022-09-08 15:57:59 +00:00
func ServePage(args []string) {
2022-09-08 15:12:06 +00:00
defer HandleExit()
2022-09-08 20:30:51 +00:00
paths := normalizePaths(args)
http.HandleFunc("/", servePageHandler(paths))
2022-09-08 15:12:06 +00:00
http.HandleFunc("/favicon.ico", doNothing)
port := strconv.Itoa(Port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}