Last active
September 7, 2015 03:12
-
-
Save IndianGuru/3231e843ddb2f5144dbc to your computer and use it in GitHub Desktop.
New dosasite.go with templates
This file contains hidden or 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" | |
| "path" | |
| ) | |
| func main() { | |
| fs := http.FileServer(http.Dir("public")) | |
| http.Handle("/public/", http.StripPrefix("/public/", fs)) | |
| http.HandleFunc("/", ServeTemplate) | |
| fmt.Println("Listening...") | |
| err := http.ListenAndServe(GetPort(), nil) | |
| if err != nil { | |
| log.Fatal("ListenAndServe: ", err) | |
| return | |
| } | |
| } | |
| // Get the Port from the environment so we can run on Heroku | |
| func GetPort() string { | |
| var port = os.Getenv("PORT") | |
| // Set a default port if there is nothing in the environment | |
| if port == "" { | |
| port = "4747" | |
| fmt.Println("INFO: No PORT environment variable detected, defaulting to " + port) | |
| } | |
| return ":" + port | |
| } | |
| func ServeTemplate(w http.ResponseWriter, r *http.Request) { | |
| lp := path.Join("templates", "layout.html") | |
| fp := path.Join("templates", r.URL.Path) | |
| // Return a 404 if the template doesn't exist | |
| info, err := os.Stat(fp) | |
| if err != nil { | |
| if os.IsNotExist(err) { | |
| http.NotFound(w, r) | |
| return | |
| } | |
| } | |
| // Return a 404 if the request is for a directory | |
| if info.IsDir() { | |
| http.NotFound(w, r) | |
| return | |
| } | |
| templates, err := template.ParseFiles(lp, fp) | |
| if err != nil { | |
| fmt.Println(err) | |
| http.Error(w, "500 Internal Server Error", 500) | |
| return | |
| } | |
| templates.ExecuteTemplate(w, "layout", nil) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment