dongxun2089 2015-11-30 01:20
浏览 203
已采纳

获取模板以正确读取Golang中的CSS文件

Hello I am having an issue with getting my template to properly display my CSS file. It is reading my imgs correctly, but anything in my CSS file does not get displayed correctly. When I run through with Delve it gets the path correctly so I am unsure what is going on. Here is my code.

package main

import (
        "bufio"
        "log"
        "net/http"
        "os"
        "strings"
        "text/template"
)

func main() {
        templates := populateTemplates()

        http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
                requestedFile := req.URL.Path[1:]
                template := templates.Lookup(requestedFile + ".html")

                if template != nil {
                        template.Execute(w, nil)
                } else {
                        w.WriteHeader(404)
                }
        })

        http.HandleFunc("/img/", serveResource)
        http.HandleFunc("/css/", serveResource)

        http.ListenAndServe(":8080", nil)
}

func serveResource(w http.ResponseWriter, req *http.Request) {
        path := "../../public" + req.URL.Path
        var contentType string
        if strings.HasSuffix(path, ".css") {
                contentType = "text/css"
        } else if strings.HasSuffix(path, ".png") {
                contentType = "image/png"
        } else {
                contentType = "text/plain"
        }

        f, err := os.Open(path)
        if err != nil {
                w.WriteHeader(404)
        } else {
                defer f.Close()
                w.Header().Add("Content Type", contentType)

                br := bufio.NewReader(f)
                br.WriteTo(w)
        }
}

func populateTemplates() *template.Template {
        result := template.New("templates")

        basePath := "../../templates"
        templateFolder, err := os.Open(basePath)
        if err != nil {
                log.Fatal(err)
        }
        defer templateFolder.Close()

        templatePathsRaw, _ := templateFolder.Readdir(-1)

        templatePaths := new([]string)
        for _, pathInfo := range templatePathsRaw {
                if !pathInfo.IsDir() {
                        *templatePaths = append(*templatePaths, basePath+"/"+pathInfo.Name())
                }
        }

        result.ParseFiles(*templatePaths...)

        return result
}

(also on http://pastebin.com/7Vcm5t75)

I have a main folder with bin, pkg, src, public, and templates in it. Then in src is a main folder that houses main.go. Public contains img, css, scripts. Img has my images in it. CSS has my CSS file in it. Then templates has my two html pages in it. Shown in tree form below:

├── bin
├── pkg
├── public
│   ├── css
│   ├── img
│   └── scripts
├── src
│   └── main
└── templates

Any help is greatly appreciated.

  • 写回答

1条回答 默认 最新

  • dsiuy42084 2015-11-30 14:55
    关注

    Used the tip above from elithrar and changed my serveResource func to read like this:

    func serveResource(w http.ResponseWriter, req *http.Request) {
        path := "../../public" + req.URL.Path
        http.ServeFile(w, req, path)
    }
    

    My issue is now resolved. Thank you!

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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站