Skip to content

Instantly share code, notes, and snippets.

@narup
Last active October 8, 2017 02:29
Show Gist options
  • Save narup/6afa89356e84e7219b0f3ec92a98ef64 to your computer and use it in GitHub Desktop.
Save narup/6afa89356e84e7219b0f3ec92a98ef64 to your computer and use it in GitHub Desktop.
func main() {
fmt.Println("Setup initialized...")
//setup all the routes
port := ":" + os.Getenv("PORT")
log.Println("Press ctrl+E to stop the server.")
srv := &http.Server{
Handler: handlers(),
Addr: port,
ReadTimeout: 4 * time.Minute,
WriteTimeout: 8 * time.Minute,
}
if serr := srv.ListenAndServe(); serr != nil {
log.Fatalf("Error starting server: %s\n", serr)
}
}
func handlers() *pweb.PhilRouter {
ctx := context.Background()
return setupRoutes(ctx)
}
func setupRoutes(ctx context.Context) *pweb.PhilRouter {
r := pweb.NewPhilRouter(ctx)
chain := alice.New()
//setup asset server, hooked train FileServer with special path requirement for httprouter
train.SetFileServer()
r.Get(train.Config.AssetsUrl+"*filepath", chain.ThenFunc(asset))
chain = chain.Append(gorilla.ClearHandler, pweb.LoggingHandler)
panicRecoverHandler := pweb.RecoverHandler(ctx, panicHandler)
chain.Append(panicRecoverHandler)
r.Get("/", chain.ThenFunc(index))
return r
}
func parseTemplates() *template.Template {
templ := template.New("application")
templ = templ.Funcs(train.HelperFuncs)
err := filepath.Walk("./views", func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, ".html") {
println(path)
_, err = templ.ParseFiles(path)
if err != nil {
log.Println(err)
}
}
return err
})
if err != nil {
panic(err)
}
return templ
}
//handles asset file request. It basically delegates the request handler to train FileServer handler
func asset(w http.ResponseWriter, r *http.Request) {
train.ServeRequest(w, r)
}
func index(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
//if util.BoolConfig("app.debug") {
templates = parseTemplates()
//}
templates.Execute(w, nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment