Skip to content

Instantly share code, notes, and snippets.

@xeoncross
Last active October 21, 2019 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xeoncross/74cce1a97a28c08a18dc2c5f7d678490 to your computer and use it in GitHub Desktop.
Save xeoncross/74cce1a97a28c08a18dc2c5f7d678490 to your computer and use it in GitHub Desktop.
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
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment