Go serving files with StripPrefix() hands on
Go serving files with StripPrefix() hands on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import (
"html/template"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", photos)
http.Handle("/resources/", http.StripPrefix("/resources", http.FileServer(http.Dir("starting-files/public"))))
log.Fatalln(http.ListenAndServe(":8080", nil))
}
func photos(w http.ResponseWriter, r *http.Request) {
tpl, err := template.ParseFiles("starting-files/templates/index.gohtml")
if err != nil {
log.Fatalln(err)
}
tpl.ExecuteTemplate(w, "index.gohtml", nil)
}
// tree starting-files
// starting-files
// ├── public
// │ └── pics
// │ ├── dog1.jpeg
// │ ├── dog2.jpeg
// │ └── dog.jpeg
// └── templates
// └── index.gohtml
// starting-files/templates/index.gohtml
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Pictures of dogs redux:</h1>
<img src="/resources/pics/dog.jpeg">
<img src="/resources/pics/dog1.jpeg">
<img src="/resources/pics/dog2.jpeg">
</body>
</html>
This post is licensed under CC BY 4.0 by the author.
