routes.go (1929B)
1 package network 2 3 import ( 4 "fmt" 5 "log" 6 "net/http" 7 "path/filepath" 8 "text/template" 9 10 mfs "codeberg.org/wtenison/miki/src/filesystem" 11 ) 12 13 var mux *http.ServeMux 14 15 func makeServerRoutes() { 16 17 mux = http.NewServeMux() 18 19 mux.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir(mfs.Dirs["web"])))) 20 21 mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { 22 http.ServeFile(w, r, filepath.Join(mfs.Dirs["web"], "/icons/favicon.ico")) 23 }) 24 25 mux.HandleFunc("/home", handleView) 26 mux.HandleFunc("/subject", handleView) 27 mux.HandleFunc("/edit", handleView) 28 29 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 30 if r.URL.Path == "/sw.js" { 31 http.ServeFile(w, r, filepath.Join(mfs.Dirs["web"], "/sw.js")) 32 } else if r.URL.Path == "/" { 33 http.Redirect(w, r, "/home", http.StatusMovedPermanently) 34 return 35 } else { 36 http.NotFound(w, r) 37 } 38 }) 39 } 40 41 func handleView(w http.ResponseWriter, r *http.Request) { 42 43 _rPkg, _err := mfs.MakeDirectoryPkg(filepath.Join(mfs.Dirs["web"], r.URL.Path), mfs.SEARCH_DEPTH_ZERO, "*.html") 44 if _err != nil { 45 log.Printf("_ERROR: network: handleView(\"/view\"): %s", _err) 46 http.NotFound(w, r) 47 return 48 } 49 50 // Add 'global' file dependencies. 51 _rPkg.DependencyFiles = append(_rPkg.DependencyFiles, mfs.WebGlobalPkg.DependencyFiles...) 52 53 // Create template from package. 54 _tmpl, _err := template.ParseFiles(_rPkg.DependencyFiles...) 55 if _err != nil { 56 _errStr := fmt.Sprintf("_ERROR: network: handleView(\"%s\"): template.ParseFiles: %s", r.URL.Path, _err) 57 log.Println(_errStr) 58 http.Error(w, _errStr, http.StatusInternalServerError) 59 return 60 } 61 62 // Render template. 63 if _err = _tmpl.ExecuteTemplate(w, "index.html", nil); _err != nil { 64 _errStr := fmt.Sprintf("_ERROR: network: handleView(\"%s\"): template.ExecuteTemplate: %s", r.URL.Path, _err) 65 log.Println(_errStr) 66 http.Error(w, _errStr, http.StatusInternalServerError) 67 return 68 } 69 }