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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line