Add static serving

This commit is contained in:
Fred Boniface committed 2023-09-04 11:08:56 +01:00
1 parent bfc14ce717
commit 073737d0e7
7 files changed
+53 -17

No files matched your search

+1
View File
@@ -0,0 +1 @@
/* EMPTY FILE */
+2 -1
View File
@@ -4,7 +4,8 @@
<meta name="charset" content="utf-8" />
<title>barcodes</title>
<link rel="icon" type="image/png" href="/favicon.png" />
<!-- CSS and JS Inclusions -->
<link rel="stylesheet" type="text/css" href="/style.css">
{{ template "head" . }}
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="author" content="Frederick Boniface" />
+4
View File
@@ -1,4 +1,8 @@
{{ define "title" }}API Documentation{{ end }}
{{ define "head" }}
{{ end }}
{{ define "body" }}
<p>API Requests can be made by making a POST request to /generate</p>
+7
View File
@@ -0,0 +1,7 @@
{{ define "title" }}barcodes{{ end }}
{{ define "head" }}
{{ end }}
{{ define "body" }}
{{ end }}
-14
View File
@@ -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)
}
+36
View File
@@ -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)
}
+3 -2
View File
@@ -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)