Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of serving templates using both the system filesystem and an in-memory fake filesystem along with custom routes
package main
import (
"log"
"net/http"
"github.com/spf13/afero"
)
func main() {
//
// v1: in memory filesystem
//
fs := afero.NewMemMapFs()
file, err := fs.Create("templates/index.html")
if err != nil {
log.Fatal(err)
}
file.Write([]byte("Home: <a href='/api'>/api</a>"))
err = file.Close()
if err != nil {
log.Fatal(err)
}
httpFs := afero.NewHttpFs(fs)
fileserver := http.FileServer(httpFs.Dir("templates"))
http.Handle("/", fileserver)
//
// v2: real filesystem
//
// http.Handle("/", http.FileServer(http.Dir("templates")))
http.Handle("/api/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("viewing /api"))
}))
http.ListenAndServe(":3000", nil)
//
// v3: Using httprouter
//
router := httprouter.New()
router.GET("/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Printf("GET /: %s\n", r.URL.Path)
http.FileServer(http.Dir(("./templates"))).ServeHTTP(w, r)
})
router.GET("/api/", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
fmt.Printf("GET /api/: %s\n", r.URL.Path)
})
http.ListenAndServe(":3000", router)
}
@Xeoncross

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.