douzhankui0758 2019-02-20 01:08
浏览 63
已采纳

去http.Handle()不能按预期工作。 找不到404档案

So I am trying to get CSS working using my Go server, but the css file is not loading correcly, I get 404 file not found. It works fine when I run Index.html straight from the browser.

My directory structure with # representing a folder and - a file:

- Main.go
# static
    - index.html
    # css
       - Styles.css

Index.html contains:

<link rel="stylesheet" type="text/css" href="css/Styles.css"/>

These are all my handlers:

muxRouter := mux.NewRouter()
muxRouter.HandleFunc("/", basicHandler)
muxRouter.HandleFunc("/ws", wsHandler)
muxRouter.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("static/css"))))

basicHandler contains:

toSend := template.HTMLEscapeString(outputMessage)
toSend = strings.Replace(toSend, "
", "<br>", -1)

templateError := allTemplates.ExecuteTemplate(responseWriter, "index.html", template.HTML(toSend))
if templateError != nil {
    log.Fatal("Template error: ", templateError)
}

wsHandler handles the websocket which my program uses.

  • 写回答

1条回答 默认 最新

  • doutan5337 2019-02-20 03:57
    关注

    I'd suggest moving your files like so (note I renamed index.html to lowercase - so it will be loaded by default when visiting the document root URL):

    Main.go
    static/
    static/index.html
    static/css/Styles.css
    

    modify index.html to refer to the more aptly named css directory:

    <link rel="stylesheet" type="text/css" href="css/Styles.css"/>
    

    EDIT: update to adjust for gorilla/mux.

    H/T to this answer.

    package main
    
    import (
            "github.com/gorilla/mux"
            "log"
            "net/http"
    )
    
    func main() {
            r := mux.NewRouter()
    
            r.PathPrefix("/css/").Handler(
                    http.StripPrefix("/css/", http.FileServer(http.Dir("static/css/"))),
            )   
    
            err := http.ListenAndServe(":8080", r)
            if err != nil {
                    log.Fatal(err)
            }   
    
            // curl 'localhost:8080/css/Styles.css'
            // <style> ...  </style>
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试