douxie5176 2018-08-01 14:58
浏览 139

使用golang服务静态文件

I'm trying to develop a simple web application but I'mhaving problem with serving my static files.

The file structure is:

  • main

--main.go

-serve

--listenAndServe.go

--templates

---login.html

---assets

----css

----fonts

----js

my code is this:

    import (
        "log"
        "net/http"
        "time"

        "github.com/gorilla/mux"
    )

    var (
        router = mux.NewRouter()
    )

    func (c *Conn) ListenAndServe() {
        fs := http.FileServer(http.Dir("./templates/assets"))
        http.Handle("/assets/", http.StripPrefix("/assets/", fs))
        router.HandleFunc("/", c.IndexPageHandler)
        router.HandleFunc("/login.html", c.LoginPageHandler)
        log.Println("Listening...")
        http.Handle("/", router)
        muxWithMiddlewares := http.TimeoutHandler(router, time.Minute*30, 
        "Timeout!")
         http.ListenAndServe(":8080", muxWithMiddlewares)
      }

But for some reason when I run it from main.go it serves the html but not the assets. I would really apreciate some tips. Thanks!

  • 写回答

1条回答 默认 最新

  • doujiao1981 2019-05-29 18:07
    关注

    Try This:

    mux.Handle("/static/", http.StripPrefix("/static", fileServer))
    

    Note that static, in your case assets only has a single forward slash within the stripPreFix function.

    Hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码