使用 gorilla mux 提供静态 html 文件

San*_*esø 4 go mux

我正在尝试根据路线提供不同的 HTML 文件。路由器对于“/”工作正常,并且它服务于index.html。然而,当转到“/download”等任何其他路径时,它也会呈现index.html,即使要提供的文件名为share.html。

我在这里做错了什么?

    package main

import (
    "net/http"
    "github.com/gorilla/mux"
    "log"
    "path"
    "fmt"
)

// main func
func main() {
    routes()
}

// routes
func routes() {
    // init router
    r := mux.NewRouter()
    // index route
    r.HandleFunc("/", home)
    r.HandleFunc("/share", share)
    r.HandleFunc("/download", download)

    // start server on port 1337
    log.Fatal(http.ListenAndServe(":1337", r))
}

// serves index file
func home(w http.ResponseWriter, r*http.Request) {
    p := path.Dir("./public/views/index.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}

// get shared files
func share(w http.ResponseWriter, r *http.Request) {
    switch r.Method {
    case "POST":
        if err := r.ParseForm(); err != nil {
            fmt.Fprint(w, "ParseForm() err: %v", err)
            return
        }
        log.Println(r.FormValue("name"))
        http.Redirect(w, r, "/download", http.StatusMovedPermanently)
    }
}

func download(w http.ResponseWriter, r *http.Request) {
    p := path.Dir("./public/views/share.html")
    // set header
    w.Header().Set("Content-type", "text/html")
    http.ServeFile(w, r, p)
}
Run Code Online (Sandbox Code Playgroud)

小智 5

我相信您可能正在寻找“PathPrefix”

func routes() {
    // init router
    r := mux.NewRouter()
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}
Run Code Online (Sandbox Code Playgroud)