post image January 6, 2022 | 1 min Read

Go serving files with StripPrefix() hands on

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>

author image

Jan Toth

I have been in DevOps related jobs for past 6 years dealing mainly with Kubernetes in AWS and on-premise as well. I spent quite a lot …

comments powered by Disqus