CSS文件未被引用。

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

CSS file doesn't get referenced

问题

我有这段代码作为我的myApp.go:

package fastaticapp

import (
	"html/template"
	"log"
	"net/http"
)

func init() {
	http.HandleFunc("/", rootHandler)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

	if r.URL.Path != "/" {
		errorHandler(w, r, http.StatusNotFound, "")
		return
	}

	page := template.Must(template.ParseFiles(
		"static/_base.html",
		"static/index.html",
	))

	if err := page.Execute(w, nil); err != nil {
		errorHandler(w, r, http.StatusInternalServerError, err.Error())
		return
	}
}

目录布局如下:

webapp/
  myApp/
    server.go
  static/
    index.html
    _base.html
    img/
    css/
     main.css

我正在使用template包和Must函数。运行开发服务器时,浏览器会渲染HTML页面,并使用开发者工具查看HTML内容。问题是css文件夹中的main.css文件似乎没有被服务器正确处理。
对此有什么想法将不胜感激。

英文:

I have this code as my myApp.go:

package fastaticapp

import (
 "html/template"
 "log"
 "net/http"
)

func init() {
http.HandleFunc("/", rootHandler)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
http.Handle("/css/", http.StripPrefix("/css/", http.FileServer(http.Dir("css"))))

if r.URL.Path != "/" {
	errorHandler(w, r, http.StatusNotFound, "")
	return
}

page := template.Must(template.ParseFiles(
	"static/_base.html",
	"static/index.html",
))

if err := page.Execute(w, nil); err != nil {
	errorHandler(w, r, http.StatusInternalServerError, err.Error())
	return
}

}

And the direcotry Layout looks like this:

webapp/
  myApp/
    server.go
  static/
    index.html
    _base.html
    img/
    css/
     main.css

I am using template package with Must function. running the dev server, the HTML page gets rendered by the browser and using developer tools I can see the html contents. The problem is main.css file within the css folder does not appear to be properly handled by the server.
Any thought on this would be highly appreciated.

答案1

得分: 2

请使用http.Dir("static/css")代替http.Dir("css")

英文:

Use

http.Dir("static/css")

instead of

http.Dir("css")

huangapple
  • 本文由 发表于 2015年3月24日 15:06:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/29226762.html
匿名

发表评论

匿名网友

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

确定