duankan8739 2015-06-28 16:00
浏览 116
已采纳

带有静态文件的http.HandleFunc

I am building a webpage. The page should be able to handle the different http methods (GET, POST...). My page technically works and handles each type of request, but in the case of GET requests (serving index.html at the root "/" path), my page is not displaying properly. None of the images or css are displaying correctly, presumably because those files cannot be found.

Ugly page

I have noticed that http.Handle provides better results than http.HandleFunc when substituted into my server.go code below, in that the images and css do display correctly using:

http.FileServer(http.Dir("static"))
http.Handle("/", http.StripPrefix("/", fs))

The following is my web server with images and css not being displayed correctly. In general, my intent is to use static files for everything, including html (ex. index.html) and to implement some solution using nothing but standard go.

server.go code

package main

import (
  "net/http"
  "fmt"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
  w.Header().Add("Content Type", "text/html")
  switch r.Method {
    case "GET":
      http.ServeFile(w, r, "./static/index.html")
    case "POST":
      fmt.Pprintf(w, "POST!")
    case "PUT":
      fmt.Pprintf(w, "PUT!")
    case "DELETE":
      fmt.Pprintf(w, "DELETE!")
    default:
      fmt.Pprintf(w, "Default!")
  }
}

func main() {
  http.HandleFunc("/", indexHandler)
  http.ListenAndServe(":3000", nil)
}
  • 写回答

1条回答 默认 最新

  • duannao3819 2015-06-28 17:42
    关注

    You've hard-coded your server to always return index.html for any GET request, no matter what is being requested. So if your index.html includes a reference to style.css, the browser is going to make a second request for style.css and you'll return index.html again.

    I assume what you're trying to do is have all GET requests return static files, while other verbs will do something else. You just need to pass those along to the file server:

    root := "static"
    ...
    case "GET":
        if r.URL.Path == "" || r.URL.Path == "/" {
            http.ServeFile(w, r, path.Join(root, "index.html"))
        } else {
            http.ServeFile(w, r, path.Join(root, r.URL.Path))
        }
    

    Note that by the time your handler is called, all ".." references in the URL have been removed, attackers can't use this to escape your static tree. But ServeFile() will return directory listings, so you'll need to check for that if that's a problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)