You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
107 lines
2.0 KiB
107 lines
2.0 KiB
package server
|
|
|
|
|
|
import (
|
|
"runtime"
|
|
"os/exec"
|
|
"html/template"
|
|
"git.nagee.dev/isthisnagee/diary/model"
|
|
"log"
|
|
"embed"
|
|
"net"
|
|
"net/http"
|
|
"fmt"
|
|
"path"
|
|
"os"
|
|
)
|
|
|
|
|
|
//go:embed templates/*
|
|
var files embed.FS
|
|
var templates map[string]*template.Template
|
|
|
|
var App *model.App
|
|
|
|
func getFreePort() (int, error) {
|
|
listener, err := net.Listen("tcp", ":0")
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
defer listener.Close()
|
|
return listener.Addr().(*net.TCPAddr).Port, nil
|
|
}
|
|
|
|
func openBrowser(url string) {
|
|
var err error
|
|
|
|
log.Print(url)
|
|
|
|
switch runtime.GOOS {
|
|
case "linux":
|
|
err = exec.Command("xdg-open", url).Start()
|
|
case "windows":
|
|
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
|
|
case "darwin":
|
|
err = exec.Command("open", url).Start()
|
|
default:
|
|
err = fmt.Errorf("unsupported platform")
|
|
}
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
}
|
|
|
|
func LoadTemplates() error {
|
|
template.PareseFS(content)
|
|
|
|
}
|
|
|
|
func Index(w http.ResponseWriter, r *http.Request) {
|
|
tmpl, err = template.ParseFS(files, "index.html")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
|
|
log.Print(tmpl)
|
|
data := App.GetDiaryEntries(model.GetDiaryEntriesQuery{})
|
|
if err := tmpl.Execute(w, data); err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
|
|
func setup() {
|
|
home, err := os.UserHomeDir()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
var db_path = path.Join(home, ".diary.sql")
|
|
app, err := model.NewApp(db_path)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
App = app
|
|
}
|
|
|
|
func Run() {
|
|
setup()
|
|
|
|
http.HandleFunc("/", Index)
|
|
|
|
port, err := getFreePort()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
log.Print("opening browser")
|
|
openBrowser(fmt.Sprintf("http://localhost:%d", port))
|
|
log.Print("done")
|
|
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
}
|