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.
diary/server/server.go

138 lines
2.4 KiB

3 years ago
package server
import (
2 years ago
"embed"
"fmt"
"html/template"
"io/fs"
"log"
"net"
"net/http"
"os"
"os/exec"
"path"
"runtime"
3 years ago
"git.nagee.dev/isthisnagee/diary/model"
)
//go:embed templates/*
var files embed.FS
2 years ago
3 years ago
var templates map[string]*template.Template
var App *model.App
2 years ago
func LoadTemplates() error {
if templates == nil {
templates = make(map[string]*template.Template)
}
tmplFiles, err := fs.ReadDir(files, "templates")
if err != nil {
return err
}
for _, tmpl := range tmplFiles {
if tmpl.IsDir() {
continue
}
pt, err := template.ParseFS(files, path.Join("templates", tmpl.Name()))
if err != nil {
return err
}
templates[tmpl.Name()] = pt
}
return nil
}
3 years ago
func getFreePort() (int, error) {
2 years ago
listener, err := net.Listen("tcp", ":0")
if err != nil {
return 0, err
}
defer listener.Close()
return listener.Addr().(*net.TCPAddr).Port, nil
3 years ago
}
func openBrowser(url string) {
var err error
2 years ago
log.Print(url)
3 years ago
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 Index(w http.ResponseWriter, r *http.Request) {
2 years ago
log.Print(templates)
var tmpl, ok = templates["index.html"]
if !ok {
http.Error(w, "could not find template index", http.StatusInternalServerError)
return
}
3 years ago
2 years ago
data := App.GetDiaryEntries(model.GetDiaryEntriesQuery{})
if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
3 years ago
func setup() {
home, err := os.UserHomeDir()
2 years ago
if err != nil {
panic(err)
}
var db_path = path.Join(home, ".diary.sql")
app, err := model.NewApp(db_path)
if err != nil {
panic(err)
}
err = LoadTemplates()
if err != nil {
panic(err)
}
App = app
3 years ago
}
2 years ago
func Run(openBrowserAtUrl bool, defaultPort int) {
setup()
3 years ago
2 years ago
http.HandleFunc("/", Index)
3 years ago
2 years ago
var port int
if defaultPort <= 0 {
freePort, err := getFreePort()
if err != nil {
panic(err)
}
port = freePort
} else {
port = defaultPort
}
3 years ago
2 years ago
log.Print("opening browser")
var url = fmt.Sprintf("http://localhost:%d", port)
log.Print(url)
if openBrowserAtUrl {
openBrowser(url)
}
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
panic(err)
}
3 years ago
}