...

Source file src/github.com/go-chi/chi/_examples/fileserver/main.go

Documentation: github.com/go-chi/chi/_examples/fileserver

     1  //
     2  // FileServer
     3  // ===========
     4  // This example demonstrates how to serve static files from your filesystem.
     5  //
     6  //
     7  // Boot the server:
     8  // ----------------
     9  // $ go run main.go
    10  //
    11  // Client requests:
    12  // ----------------
    13  // $ curl http://localhost:3333/files/
    14  // <pre>
    15  // <a href="notes.txt">notes.txt</a>
    16  // </pre>
    17  //
    18  // $ curl http://localhost:3333/files/notes.txt
    19  // Notessszzz
    20  //
    21  package main
    22  
    23  import (
    24  	"net/http"
    25  	"os"
    26  	"path/filepath"
    27  	"strings"
    28  
    29  	"github.com/go-chi/chi"
    30  	"github.com/go-chi/chi/middleware"
    31  )
    32  
    33  func main() {
    34  	r := chi.NewRouter()
    35  	r.Use(middleware.Logger)
    36  
    37  	// Index handler
    38  	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    39  		w.Write([]byte("hi"))
    40  	})
    41  
    42  	// Create a route along /files that will serve contents from
    43  	// the ./data/ folder.
    44  	workDir, _ := os.Getwd()
    45  	filesDir := http.Dir(filepath.Join(workDir, "data"))
    46  	FileServer(r, "/files", filesDir)
    47  
    48  	http.ListenAndServe(":3333", r)
    49  }
    50  
    51  // FileServer conveniently sets up a http.FileServer handler to serve
    52  // static files from a http.FileSystem.
    53  func FileServer(r chi.Router, path string, root http.FileSystem) {
    54  	if strings.ContainsAny(path, "{}*") {
    55  		panic("FileServer does not permit any URL parameters.")
    56  	}
    57  
    58  	if path != "/" && path[len(path)-1] != '/' {
    59  		r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
    60  		path += "/"
    61  	}
    62  	path += "*"
    63  
    64  	r.Get(path, func(w http.ResponseWriter, r *http.Request) {
    65  		rctx := chi.RouteContext(r.Context())
    66  		pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
    67  		fs := http.StripPrefix(pathPrefix, http.FileServer(root))
    68  		fs.ServeHTTP(w, r)
    69  	})
    70  }
    71  

View as plain text