http.go (view raw)
1package main
2
3import (
4 "fmt"
5 "html/template"
6 "log"
7 "net/http"
8 "path"
9 "strings"
10)
11
12var t *template.Template
13
14// TODO somewhat better error handling
15const InternalServerErrorMsg = "500: Internal Server Error"
16
17func renderError(w http.ResponseWriter, errorMsg string, statusCode int) { // TODO think about pointers
18 data := struct{ ErrorMsg string }{errorMsg}
19 err := t.ExecuteTemplate(w, "error.html", data)
20 if err != nil { // shouldn't happen probably
21 http.Error(w, errorMsg, statusCode)
22 }
23}
24
25func indexHandler(w http.ResponseWriter, r *http.Request) {
26 indexFiles, err := getIndexFiles()
27 if err != nil {
28 log.Println(err)
29 renderError(w, InternalServerErrorMsg, 500)
30 return
31 }
32 allUsers, err := getUsers()
33 if err != nil {
34 log.Println(err)
35 renderError(w, InternalServerErrorMsg, 500)
36 return
37 }
38 data := struct {
39 Domain string
40 PageTitle string
41 Files []*File
42 Users []string
43 }{c.RootDomain, c.SiteTitle, indexFiles, allUsers}
44 err = t.ExecuteTemplate(w, "index.html", data)
45 if err != nil {
46 log.Println(err)
47 renderError(w, InternalServerErrorMsg, 500)
48 return
49 }
50
51}
52
53func editFileHandler(w http.ResponseWriter, r *http.Request) {
54 // get vs post
55 // read file content
56 authUser := "alex"
57 files, _ := getUserFiles(authUser)
58 for _, file := range files {
59 fmt.Fprintf(w, "%s\n", file.Name)
60 }
61}
62
63func mySiteHandler(w http.ResponseWriter, r *http.Request) {
64 authUser := "alex"
65 files, _ := getUserFiles(authUser)
66 for _, file := range files {
67 fmt.Fprintf(w, "%s\n", file.Name)
68 }
69}
70
71// Server a user's file
72func userFile(w http.ResponseWriter, r *http.Request) {
73 userName := strings.Split(r.Host, ".")[0]
74 fileName := path.Join(c.FilesDirectory, userName, r.URL.Path)
75 http.ServeFile(w, r, fileName)
76}
77
78func runHTTPServer() {
79 log.Println("Running http server")
80 var err error
81 t, err = template.ParseGlob("./templates/*.html") // TODO make template dir configruable
82 if err != nil {
83 log.Fatal(err)
84 }
85 http.HandleFunc(c.RootDomain+"/", indexHandler)
86 http.HandleFunc(c.RootDomain+"/my_site", mySiteHandler)
87 http.HandleFunc(c.RootDomain+"/edit/", editFileHandler)
88 // http.HandleFunc("/delete/", deleteFileHandler)
89 // login+register functions
90 http.HandleFunc("/", userFile)
91 log.Fatal(http.ListenAndServe(":8080", logRequest(http.DefaultServeMux)))
92}
93
94func logRequest(handler http.Handler) http.Handler {
95 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
96 log.Printf("%s %s %s\n", r.RemoteAddr, r.Method, r.URL)
97 })
98}