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 w.WriteHeader(http.StatusInternalServerError)
21 log.Println(errorMsg)
22 data := struct{ ErrorMsg string }{errorMsg}
23 err := t.ExecuteTemplate(w, "error.html", data)
24 if err != nil { // shouldn't happen probably
25 fmt.Fprintf(w, errorMsg)
26 }
27}
28
29func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
30 indexFiles, err := getIndexFiles()
31 if err != nil {
32 renderError(w, InternalServerError)
33 return
34 }
35 allUsers, err := getUsers()
36 if err != nil {
37 renderError(w, InternalServerError)
38 return
39 }
40 data := struct {
41 Domain string
42 PageTitle string
43 Files []*File
44 Users []string
45 }{h.Domain, h.SiteTitle, indexFiles, allUsers}
46 err = t.ExecuteTemplate(w, "index.html", data)
47 if err != nil {
48 renderError(w, InternalServerError)
49 return
50 }
51
52}
53
54func editFileHandler(w http.ResponseWriter, r *http.Request) {
55 // get vs post
56 // read file content
57 authUser := "alex"
58 files, _ := getUserFiles(authUser)
59 for _, file := range files {
60 fmt.Fprintf(w, "%s\n", file.Name)
61 }
62}
63
64func mySiteHandler(w http.ResponseWriter, r *http.Request) {
65 authUser := "alex"
66 files, _ := getUserFiles(authUser)
67 for _, file := range files {
68 fmt.Fprintf(w, "%s\n", file.Name)
69 }
70}
71
72func runHTTPServer(config *Config) {
73 var err error
74 t, err = template.ParseGlob("./templates/*.html") // TODO make template dir configruable
75 if err != nil {
76 log.Fatal(err)
77 }
78 http.Handle("/", &IndexHandler{config.RootDomain, config.SiteTitle})
79 http.HandleFunc("/my_site", mySiteHandler)
80 http.HandleFunc("/edit/", editFileHandler)
81 // http.HandleFunc("/delete/", deleteFileHandler)
82 // login+register functions
83 log.Fatal(http.ListenAndServe(":8080", nil))
84}