diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..9fdc130 --- /dev/null +++ b/static/style.css @@ -0,0 +1 @@ +/* EMPTY FILE */ \ No newline at end of file diff --git a/templates/base.html b/templates/base.html index 484b033..7c7e5b8 100644 --- a/templates/base.html +++ b/templates/base.html @@ -4,7 +4,8 @@ barcodes - + + {{ template "head" . }} diff --git a/templates/help.html b/templates/help.html index 3b206af..0ff2819 100644 --- a/templates/help.html +++ b/templates/help.html @@ -1,4 +1,8 @@ {{ define "title" }}API Documentation{{ end }} + +{{ define "head" }} +{{ end }} + {{ define "body" }}

API Requests can be made by making a POST request to /generate

diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..b95951b --- /dev/null +++ b/templates/index.html @@ -0,0 +1,7 @@ +{{ define "title" }}barcodes{{ end }} + +{{ define "head" }} +{{ end }} + +{{ define "body" }} +{{ end }} \ No newline at end of file diff --git a/web/page.route.go b/web/page.route.go deleted file mode 100644 index 10b79a9..0000000 --- a/web/page.route.go +++ /dev/null @@ -1,14 +0,0 @@ -package web - -import ( - "fmt" - "net/http" - "strings" -) - -func mainHandler(w http.ResponseWriter, r *http.Request) { - fmt.Println("Request URL: ", r.URL.Path) - requestFile := strings.TrimRight(r.URL.Path, "/") - requestFile = strings.TrimRight(requestFile, ".html") - fmt.Println("Template File: ", requestFile) -} diff --git a/web/root.route.go b/web/root.route.go new file mode 100644 index 0000000..dedf8b5 --- /dev/null +++ b/web/root.route.go @@ -0,0 +1,36 @@ +package web + +import ( + "fmt" + "html/template" + "net/http" + "os" +) + +func rootHandler(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + if path == "/" { + path = "/index" + } + + templatePath := "templates" + path + ".html" + if _, err := os.Stat(templatePath); err == nil { + tmpl, err := template.ParseFiles("templates/base.html", templatePath) + if err != nil { + fmt.Println("Error parsing template: ", err) + http.Error(w, "Error parsing template", http.StatusInternalServerError) + return + } + tmpl.Execute(w, nil) + return + } + + staticPath := "static" + path + if _, err := os.Stat(staticPath); err == nil { + http.ServeFile(w, r, staticPath) + return + } + + // Return a 404 if the file does not exist in either directory. + http.NotFound(w, r) +} diff --git a/web/server.go b/web/server.go index 8240cff..c4fd63f 100644 --- a/web/server.go +++ b/web/server.go @@ -9,9 +9,10 @@ func StartServer() { // What I want to do here is server from /static // if the resource exists, else try to render from /templates // if the template exists. Else return 404. - http.HandleFunc("/", mainHandler) - http.HandleFunc("/help", helpTemplate) + http.HandleFunc("/", rootHandler) + + http.HandleFunc("/help", helpTemplate) // Rendered with props passed in http.HandleFunc("/generate", generateBarcode)