Last active
October 21, 2019 15:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More reading: https://stackoverflow.com/questions/16742331/how-to-mock-abstract-filesystem-in-go