dowaw80220 2018-06-01 22:08
浏览 55

使用大猩猩多路复用器服务静态html文件

I'm trying to serve different HTML files depending on the route. The router works fine for "/" and it serves the index.html. However when going to any other route like "/download", it also renders the index.html, even tho the file that is to be served is called share.html.

What am I doing wrong here?

    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)
}
  • 写回答

2条回答 默认 最新

  • dqcj32855 2018-06-01 23:33
    关注

    Remove all calls to path.Dir(). This call returns the directory part of the path. The code serves index.html because ServeFile looks for index.html when given a directory.

    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装