Mercurial > famtree
comparison 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 |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:a17a4894f4bd |
---|---|
1 package main | |
2 | |
3 import ( | |
4 "os" | |
5 "fmt" | |
6 "errors" | |
7 "html/template" | |
8 "log" | |
9 "net/http" | |
10 "regexp" | |
11 ) | |
12 | |
13 type ApiReq struct { | |
14 endpoint string | |
15 } | |
16 | |
17 type Page struct { | |
18 Title string | |
19 Content []byte | |
20 } | |
21 | |
22 func (p *Page) save() error { | |
23 filename := p.Title + ".txt" | |
24 return os.WriteFile(filename, p.Content, 0600) | |
25 } | |
26 | |
27 func loadPage(title string) ( *Page, error ) { | |
28 filename := title + ".txt" | |
29 body, err := os.ReadFile(filename) | |
30 if err != nil { | |
31 return nil, err | |
32 } | |
33 return &Page{Title: title, Content: body}, nil | |
34 } | |
35 | |
36 func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) { | |
37 t, err := template.ParseFiles( "views/" + tmpl + ".html" ) | |
38 if err != nil { | |
39 http.Error( w, err.Error(), http.StatusInternalServerError ) | |
40 return | |
41 } | |
42 err = t.Execute( w, p ) | |
43 if err != nil { | |
44 http.Error( w, err.Error(), http.StatusInternalServerError ) | |
45 return | |
46 } | |
47 } | |
48 | |
49 func apiHandler(w http.ResponseWriter, r *http.Request) { | |
50 endpoint, _ := getTitle( w, r ) | |
51 log.Printf(`API Request: %s`, endpoint ) | |
52 } | |
53 | |
54 func errorViewHandler(w http.ResponseWriter, r *http.Request) { | |
55 title, _ := getTitle( w, r ) | |
56 log.Printf( `Rendering error page: %s`, title ) | |
57 p := &Page{ Title: title } | |
58 renderTemplate( w, "error", p ) | |
59 } | |
60 func viewHandler(w http.ResponseWriter, r *http.Request) { | |
61 title, err := getTitle( w, r ) | |
62 if err != nil { title = "404" } | |
63 log.Printf( `Rendering page: %s`, title ) | |
64 p, err := loadPage( title ) | |
65 if err != nil { | |
66 http.Redirect( w, r, "/error/404", http.StatusFound ) | |
67 return | |
68 } | |
69 renderTemplate( w, "test", p ) | |
70 } | |
71 | |
72 var validPath = regexp.MustCompile( "^/(view|error|api)/([a-zA-Z0-9]+)$" ) | |
73 func getTitle( w http.ResponseWriter, r *http.Request ) ( string, error ) { | |
74 m := validPath.FindStringSubmatch( r.URL.Path ) | |
75 if m == nil { | |
76 http.NotFound( w, r ) | |
77 return "", errors.New("Unsupported Route") | |
78 } | |
79 return m[2], nil | |
80 } | |
81 | |
82 func main() { | |
83 http.HandleFunc("/view/", viewHandler) | |
84 http.HandleFunc("/error/", errorViewHandler) | |
85 http.HandleFunc("/api/", apiHandler) | |
86 | |
87 fmt.Printf("Server Running") | |
88 | |
89 log.Fatal(http.ListenAndServe(":8080", nil)) | |
90 } | |
91 |