首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用gorilla mux提供静态html文件

使用gorilla mux提供静态html文件
EN

Stack Overflow用户
提问于 2018-06-02 06:08:47
回答 2查看 3.7K关注 0票数 3

我正在尝试根据路由提供不同的HTML文件。路由器可以很好地处理"/“,并为index.html提供服务。然而,当转到像"/download“这样的任何其他路由时,它也会呈现index.html,即使要提供的文件名为share.html。

我在这里做错了什么?

代码语言:javascript
复制
    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)
}
EN

回答 2

Stack Overflow用户

发布于 2019-05-31 15:46:38

我相信你可能在找"PathPrefix“

代码语言:javascript
复制
func routes() {
    // init router
    r := mux.NewRouter()
    r.PathPrefix("/").Handler(http.FileServer(http.Dir("./public/views/")))
}
票数 4
EN

Stack Overflow用户

发布于 2018-06-02 07:33:52

删除对path.Dir()的所有调用。此调用返回路径的目录部分。该代码服务于index.html,因为ServeFile会在给定目录时查找index.html。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50651523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档