Browse Source

Serve files

Gildas Chabot 4 years ago
parent
commit
7db1a5c09e
4 changed files with 22 additions and 5 deletions
  1. 5 0
      files.go
  2. 15 3
      pages/pages.go
  3. 1 1
      templates/files.html
  4. 1 1
      templates/movie.html

+ 5 - 0
files.go

@@ -2,6 +2,7 @@ package movies
2 2
 
3 3
 import (
4 4
 	"fmt"
5
+	"net/http"
5 6
 	"os"
6 7
 	"path/filepath"
7 8
 	"strings"
@@ -61,3 +62,7 @@ func stringContainsAll(path string, split []string) bool {
61 62
 	}
62 63
 	return true
63 64
 }
65
+
66
+func (fs *FileSource) Serve(w http.ResponseWriter, r *http.Request, file string) {
67
+	http.ServeFile(w, r, file)
68
+}

+ 15 - 3
pages/pages.go

@@ -18,6 +18,7 @@ func Router(c *movies.Collection) http.HandlerFunc {
18 18
 	movieHandler := Movie(c)
19 19
 	listHandler := List(c)
20 20
 	filesHandler := Files(c)
21
+	fileHandler := File(c, "/files/")
21 22
 
22 23
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23 24
 		path := r.URL.Path
@@ -25,9 +26,6 @@ func Router(c *movies.Collection) http.HandlerFunc {
25 26
 		case path == "/":
26 27
 			homeHandler(w, r)
27 28
 			return
28
-		case path == "/files":
29
-			filesHandler(w, r)
30
-			return
31 29
 		case path == "/style.css":
32 30
 			http.ServeFile(w, r, "templates/style.css")
33 31
 			return
@@ -37,6 +35,12 @@ func Router(c *movies.Collection) http.HandlerFunc {
37 35
 		case strings.HasPrefix(path, "/tt"):
38 36
 			movieHandler(w, r)
39 37
 			return
38
+		case path == "/files":
39
+			filesHandler(w, r)
40
+			return
41
+		case strings.HasPrefix(path, "/files/"):
42
+			fileHandler(w, r)
43
+			return
40 44
 		}
41 45
 	})
42 46
 }
@@ -244,3 +248,11 @@ func Files(c *movies.Collection) http.HandlerFunc {
244 248
 		})
245 249
 	})
246 250
 }
251
+
252
+func File(c *movies.Collection, prefix string) http.HandlerFunc {
253
+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
254
+		file := "/" + strings.TrimPrefix(r.URL.Path, prefix)
255
+
256
+		c.Files.Serve(w, r, file)
257
+	})
258
+}

+ 1 - 1
templates/files.html

@@ -18,7 +18,7 @@
18 18
 
19 19
         <ul class="file-list">
20 20
             {{ range $f := .Files }}
21
-            <li>{{ $f }}</li>
21
+            <li><a href="/files/{{ $f }}">{{ $f }}</a></li>
22 22
             {{ end }}
23 23
         </ul>
24 24
     </body>

+ 1 - 1
templates/movie.html

@@ -20,7 +20,7 @@
20 20
 
21 21
         <ul class="file-list">
22 22
             {{ range $f := .Movie.Files }}
23
-            <li>{{ $f }}</li>
23
+            <li><a href="/files/{{ $f }}">{{ $f }}</a></li>
24 24
             {{ end }}
25 25
         </ul>
26 26