menu

arrow_back File server in golang?

by
1 vote
Used this code for static files
func main() {
http.Handle("/", http.FileServer(http.Dir("./files")))
http.ListenAndServe(":5000", nil)
}

Then came the need to expand the application. Added routing

package main
import (
"net/http"
"github.com/gorilla/mux"
"fmt"
)

func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", Index)
router.HandleFunc("/files/", FileServer)

http.ListenAndServe(":5000", router)
}

func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "hi. This is the main page")
}

func FileServer(w http.ResponseWriter, r *http.Request) {
http.FileServer(http.Dir("./files"))
}
--------------
But static files are not loaded. Necessary, what would the link site/files/css/my.css was loaded the corresponding file
I and routing to make and filserver what would be?

2 Comments

Can give an example?
Wrap code in tags

1 Answer

by
 
Best answer
0 votes
router := mux.NewRouter()
s := http.StripPrefix("/files/", http.FileServer(http.Dir("./files/")))
router.HandleFunc("/", Index)
router.PathPrefix("/files/").Handler(s)
http.Handle("/", router)
http.ListenAndServe(":5000", nil)