isthisnagee 3 years ago
parent ba188c53ee
commit 0ab9bca213

@ -0,0 +1,24 @@
/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd
import (
"github.com/spf13/cobra"
"git.nagee.dev/isthisnagee/diary/server"
)
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Run a web server at the specified port",
Long: `Run a web server at the specified port. Allows you to view, edit, and delete notes from a UI`,
Run: func(cmd *cobra.Command, args []string) {
server.Run()
},
}
func init() {
rootCmd.AddCommand(serveCmd)
}

@ -0,0 +1,106 @@
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)
}
}

@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML 5 Boilerplate</title>
</head>
<body>
<h1>diary</h1>
<ul>
{{ range . }}
<li>{{ .Title }}</li>
{{ end }}
</ul>
</body>
</html>
Loading…
Cancel
Save