http.go (view raw)
1package main
2
3import (
4 "fmt"
5 "html/template"
6 "log"
7 "net/http"
8)
9
10var t *template.Template
11
12type IndexHandler struct {
13 Domain string
14 SiteTitle string
15}
16
17const InternalServerError = "500: Internal Server Error"
18
19func renderError(w http.ResponseWriter, errorMsg string) { // TODO think about pointers
20 log.Println(errorMsg)
21 data := struct{ ErrorMsg string }{errorMsg}
22 err := t.ExecuteTemplate(w, "error.html", data)
23 if err != nil { // shouldn't happen probably
24 fmt.Fprintf(w, errorMsg)
25 }
26}
27
28func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
29 indexFiles, err := getIndexFiles()
30 if err != nil {
31 w.WriteHeader(http.StatusInternalServerError)
32 renderError(w, InternalServerError)
33 return
34 }
35 allUsers, err := getUsers()
36 if err != nil {
37 w.WriteHeader(http.StatusInternalServerError)
38 renderError(w, InternalServerError)
39 return
40 }
41 data := struct {
42 Domain string
43 PageTitle string
44 Files []*File
45 Users []string
46 }{h.Domain, h.SiteTitle, indexFiles, allUsers}
47 err = t.ExecuteTemplate(w, "index.html", data)
48 if err != nil {
49 w.WriteHeader(http.StatusInternalServerError)
50 renderError(w, InternalServerError)
51 return
52 }
53
54}
55
56func editFileHandler(w http.ResponseWriter, r *http.Request) {
57 // get vs post
58 // read file content
59 authUser := "alex"
60 files, _ := getUserFiles(authUser)
61 for _, file := range files {
62 fmt.Fprintf(w, "%s\n", file.Name)
63 }
64}
65
66func mySiteHandler(w http.ResponseWriter, r *http.Request) {
67 authUser := "alex"
68 files, _ := getUserFiles(authUser)
69 for _, file := range files {
70 fmt.Fprintf(w, "%s\n", file.Name)
71 }
72}
73
74func runHTTPServer(config *Config) {
75 var err error
76 t, err = template.ParseGlob("./templates/*.html") // TODO make template dir configruable
77 if err != nil {
78 log.Fatal(err)
79 }
80 http.Handle("/", &IndexHandler{config.RootDomain, config.SiteTitle})
81 http.HandleFunc("/my_site", mySiteHandler)
82 http.HandleFunc("/edit/", editFileHandler)
83 // http.HandleFunc("/delete/", deleteFileHandler)
84 // login+register functions
85 log.Fatal(http.ListenAndServe(":8080", nil))
86}