69 lines
1.5 KiB
Go
69 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/writeas/web-core/log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"runtime/debug"
|
|
"time"
|
|
)
|
|
|
|
func viewPage(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
defer func() {
|
|
if e := recover(); e != nil {
|
|
log.Error("%s: %s", e, debug.Stack())
|
|
http.Error(w, "Error", http.StatusInternalServerError)
|
|
}
|
|
|
|
log.Info(fmt.Sprintf("\"%s %s\" %s \"%s\"", r.Method, r.RequestURI, time.Since(start), r.UserAgent()))
|
|
}()
|
|
|
|
name := r.URL.Path[1:]
|
|
if name == "" {
|
|
name = "index"
|
|
}
|
|
|
|
// Make sure the page exists
|
|
if _, err := os.Stat(filepath.Join(pagesDir, name+".tmpl")); os.IsNotExist(err) {
|
|
log.Info(filepath.Join(pagesDir, name, "index.tmpl"))
|
|
if _, err := os.Stat(filepath.Join(pagesDir, name, "index.tmpl")); os.IsNotExist(err) {
|
|
t, err := getTemplate("404")
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
err = t.ExecuteTemplate(w, "base", nil)
|
|
if err != nil {
|
|
log.Info("Unable to render 404 page: %s", err)
|
|
}
|
|
return
|
|
} else {
|
|
name = filepath.Join(name, "index")
|
|
log.Info("name is now %s", name)
|
|
}
|
|
}
|
|
|
|
// Render the page
|
|
t, err := getTemplate(name)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
p := struct {
|
|
Path string
|
|
}{
|
|
Path: name,
|
|
}
|
|
|
|
err = t.ExecuteTemplate(w, "base", p)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|