initial server

server
nagee 2 years ago
parent e91153fa8f
commit 4c6342bc7c

@ -21,7 +21,7 @@ var files embed.FS
var templates map[string]*template.Template var templates map[string]*template.Template
var App *model.App type App struct{ *model.App }
func LoadTemplates() error { func LoadTemplates() error {
if templates == nil { if templates == nil {
@ -77,21 +77,20 @@ func openBrowser(url string) {
} }
func Index(w http.ResponseWriter, r *http.Request) { func (app *App) ListDiaryEntries(w http.ResponseWriter, r *http.Request) {
log.Print(templates)
var tmpl, ok = templates["index.html"] var tmpl, ok = templates["index.html"]
if !ok { if !ok {
http.Error(w, "could not find template index", http.StatusInternalServerError) http.Error(w, "could not find template index", http.StatusInternalServerError)
return return
} }
data := App.GetDiaryEntries(model.GetDiaryEntriesQuery{}) data := app.GetDiaryEntries(model.GetDiaryEntriesQuery{})
if err := tmpl.Execute(w, data); err != nil { if err := tmpl.Execute(w, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) http.Error(w, err.Error(), http.StatusInternalServerError)
} }
} }
func setup() { func setup() *App {
home, err := os.UserHomeDir() home, err := os.UserHomeDir()
if err != nil { if err != nil {
panic(err) panic(err)
@ -105,13 +104,13 @@ func setup() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
App = app return &App{app}
} }
func Run(openBrowserAtUrl bool, defaultPort int) { func Run(openBrowserAtUrl bool, defaultPort int) {
setup() app := setup()
http.HandleFunc("/", Index) http.HandleFunc("/", app.ListDiaryEntries)
var port int var port int
if defaultPort <= 0 { if defaultPort <= 0 {
@ -124,10 +123,10 @@ func Run(openBrowserAtUrl bool, defaultPort int) {
port = defaultPort port = defaultPort
} }
log.Print("opening browser")
var url = fmt.Sprintf("http://localhost:%d", port) var url = fmt.Sprintf("http://localhost:%d", port)
log.Print(url) log.Print(url)
if openBrowserAtUrl { if openBrowserAtUrl {
log.Print("opening browser")
openBrowser(url) openBrowser(url)
} }
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil { if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {

Loading…
Cancel
Save