Last active
April 8, 2021 18:39
-
-
Save llimllib/0212ea2c8b3aae0746dae9f64c930626 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"html/template" | |
"log" | |
"net/http" | |
"os" | |
) | |
func renderTemplate(w http.ResponseWriter, name string, data interface{}) { | |
// This is inefficient - it reads the templates from the filesystem every | |
// time. This makes it much easier to develop though, so we can edit our | |
// templates and the changes will be reflected without having to restart | |
// the app. | |
t, err := template.ParseGlob("templates/*.html") | |
if err != nil { | |
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500) | |
return | |
} | |
err = t.ExecuteTemplate(w, name, data) | |
if err != nil { | |
http.Error(w, fmt.Sprintf("Error %s", err.Error()), 500) | |
return | |
} | |
} | |
func index(w http.ResponseWriter, r *http.Request) { | |
renderTemplate(w, "index.html", struct { | |
Name string | |
}{ | |
Name: "Sonic the Hedgehog", | |
}) | |
} | |
func logreq(f func(w http.ResponseWriter, r *http.Request)) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
log.Printf("path: %s", r.URL.Path) | |
f(w, r) | |
}) | |
} | |
type App struct { | |
Port string | |
} | |
func (a *App) Start() { | |
http.Handle("/", logreq(index)) | |
addr := fmt.Sprintf(":%s", a.Port) | |
log.Printf("Starting app on %s", addr) | |
log.Fatal(http.ListenAndServe(addr, nil)) | |
} | |
func env(key, adefault string) string { | |
val, ok := os.LookupEnv(key) | |
if !ok { | |
return adefault | |
} | |
return val | |
} | |
func main() { | |
server := App{ | |
Port: env("PORT", "8080"), | |
} | |
server.Start() | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html><head><title>Home Page</title> | |
</head> | |
<body> | |
Hello <strong>{{.Name}}</strong> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment