Mercurial > famtree
view backend/main.go @ 0:a17a4894f4bd draft default tip
Initial commit converting git to mercurial
author | Alfred Burgess <aburgess@ucc.asn.au> |
---|---|
date | Sun, 14 Apr 2024 19:35:23 +0800 |
parents | |
children |
line wrap: on
line source
package main import ( "os" "fmt" "errors" "html/template" "log" "net/http" "regexp" ) type ApiReq struct { endpoint string } type Page struct { Title string Content []byte } func (p *Page) save() error { filename := p.Title + ".txt" return os.WriteFile(filename, p.Content, 0600) } func loadPage(title string) ( *Page, error ) { filename := title + ".txt" body, err := os.ReadFile(filename) if err != nil { return nil, err } return &Page{Title: title, Content: body}, nil } func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { t, err := template.ParseFiles( "views/" + tmpl + ".html" ) if err != nil { http.Error( w, err.Error(), http.StatusInternalServerError ) return } err = t.Execute( w, p ) if err != nil { http.Error( w, err.Error(), http.StatusInternalServerError ) return } } func apiHandler(w http.ResponseWriter, r *http.Request) { endpoint, _ := getTitle( w, r ) log.Printf(`API Request: %s`, endpoint ) } func errorViewHandler(w http.ResponseWriter, r *http.Request) { title, _ := getTitle( w, r ) log.Printf( `Rendering error page: %s`, title ) p := &Page{ Title: title } renderTemplate( w, "error", p ) } func viewHandler(w http.ResponseWriter, r *http.Request) { title, err := getTitle( w, r ) if err != nil { title = "404" } log.Printf( `Rendering page: %s`, title ) p, err := loadPage( title ) if err != nil { http.Redirect( w, r, "/error/404", http.StatusFound ) return } renderTemplate( w, "test", p ) } var validPath = regexp.MustCompile( "^/(view|error|api)/([a-zA-Z0-9]+)$" ) func getTitle( w http.ResponseWriter, r *http.Request ) ( string, error ) { m := validPath.FindStringSubmatch( r.URL.Path ) if m == nil { http.NotFound( w, r ) return "", errors.New("Unsupported Route") } return m[2], nil } func main() { http.HandleFunc("/view/", viewHandler) http.HandleFunc("/error/", errorViewHandler) http.HandleFunc("/api/", apiHandler) fmt.Printf("Server Running") log.Fatal(http.ListenAndServe(":8080", nil)) }