Skip to content

Commit

Permalink
fix: more explicit error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
jnsgruk committed Aug 9, 2024
1 parent 6e26874 commit d9da73c
Showing 1 changed file with 25 additions and 12 deletions.
37 changes: 25 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ type LibationsPageData struct {

// parseTemplates is used to parse templates from the embedded FS, and ensure that the
// 'StringJoin' function is available to the templates.
func parseTemplates() *template.Template {
func parseTemplates() (*template.Template, error) {
// Create an fs.FS from the embedded filesystem
files, err := fs.Sub(templateFS, "templates")
if err != nil {
Expand All @@ -62,8 +62,13 @@ func parseTemplates() *template.Template {

funcMap := template.FuncMap{"StringsJoin": strings.Join}
tmpl := template.New("").Funcs(funcMap)
tmpl, _ = tmpl.ParseFS(files, "*.html", "icons/*.svg")
return tmpl

tmpl, err = tmpl.ParseFS(files, "*.html", "icons/*.svg")
if err != nil {
return nil, err
}

return tmpl, nil
}

// parseRecipes attempts to read and parse recipes either from a path specified at the CLI,
Expand Down Expand Up @@ -103,7 +108,11 @@ func libationsMux(drinks []Drink, files fs.FS) *http.ServeMux {
// Serve static files from our embedded filesystem using http.Fileserver
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(files))))

templates := parseTemplates()
templates, err := parseTemplates()
if err != nil {
slog.Error("failed to parse templates from filesystem", "error", err.Error())
os.Exit(1)
}

// Render the templates with the drinks/time data.
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -196,32 +205,36 @@ func main() {
// Create an fs.FS from the embedded filesystem
files, err := fs.Sub(staticFS, "static")
if err != nil {
slog.Error(err.Error())
slog.Error("failed to access static files in embedded filesystem", "error", err.Error())
os.Exit(1)
}

drinks, err := parseRecipes(*recipesFile)
if err != nil {
slog.Error(err.Error())
slog.Error("failed to parse recipes", "error", err.Error())
os.Exit(1)
}

var listener *net.Listener
if *local {
listener, err = localListener(*addr)
if err != nil {
slog.Error("failed to create local listener", "error", err.Error())
os.Exit(1)
}
} else {
listener, err = tailscaleListener(*hostname, *tsnetLogs)
}

if err != nil {
slog.Error(err.Error())
os.Exit(1)
if err != nil {
slog.Error("failed to create tailscale listener", "error", err.Error())
os.Exit(1)
}
}

mux := libationsMux(drinks, files)

slog.Info(fmt.Sprintf("starting listener on %s", *addr))
if err = http.Serve(*listener, mux); err != nil {
slog.Error(err.Error())
slog.Error("failed to start http server", "error", err.Error())
os.Exit(1)
}
}

0 comments on commit d9da73c

Please sign in to comment.