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

huangapple go评论99阅读模式
英文:

Getting template to properly read CSS file in Golang

问题

你好,我遇到了一个问题,无法正确显示我的CSS文件。它可以正确读取我的图片,但是CSS文件中的内容无法正确显示。当我使用Delve运行时,它可以正确获取路径,所以我不确定出了什么问题。以下是我的代码。

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
}

我有一个主文件夹,其中包含bin、pkg、src、public和templates文件夹。然后在src文件夹中有一个包含main.go的main文件夹。public文件夹包含img、css和scripts文件夹。img文件夹中有我的图片,css文件夹中有我的CSS文件,templates文件夹中有我的两个HTML页面。树形结构如下所示:

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

非常感谢您的帮助。

英文:

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

得分: 3

使用了elithrar上面的提示,并将我的serveResource函数更改为以下内容:

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

我的问题现在已解决。谢谢!

英文:

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!

huangapple
  • 本文由 发表于 2015年11月30日 09:20:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/33990145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定