英文:
Memory error, html/template in Go
问题
当尝试执行这段代码时,我遇到了一些内存错误:
package web
import (
"net/http"
"html/template"
)
type Hello struct {
Level string
}
func Main(w http.ResponseWriter, r *http.Request) {
h := Hello{Level: "gsdfg"}
t, _ := template.ParseFiles("web.html")
t.Execute(w, h)
}
我在浏览器中收到的错误消息是:
the runtime process gave a bad HTTP response: ''
2015/03/26 11:34:56 http: panic serving 127.0.0.1:43269: runtime error: invalid memory address or nil pointer dereference
我不明白我做错了什么...
英文:
I get some memory error when trying to execute this code:
package web
import (
"net/http"
"html/template"
)
type Hello struct {
Level string
}
func Main(w http.ResponseWriter, r *http.Request) {
h := Hello{Level: "gsdfg"}
t, _ := template.ParseFiles("web.html")
t.Execute(w, h)
}
The error message I get in the browser is this:
the runtime process gave a bad HTTP response: ''
2015/03/26 11:34:56 http: panic serving 127.0.0.1:43269: runtime error: invalid memory address or nil pointer dereference
I dont understand what I am doing wrong...
答案1
得分: 3
template.ParseFiles 返回一个错误
func ParseFiles(filenames ...string) (*Template, error)
> 如果发生错误,解析将停止,并且返回的 *Template
为 nil。
你应该检查错误,以防有问题。这可能解释了为什么 t
可能为 nil。
通常来说,最佳实践是永远不要忽略错误。
在这里:
var t *Template
if t, err := template.ParseFiles("web.html"); err != nil {
// 做一些处理
// 返回 err
// 或者
// panic(err)
}
英文:
template.ParseFiles returns an error
func ParseFiles(filenames ...string) (*Template, error)
> If an error occurs, parsing stops and the returned *Template
is nil.
You should check the error in case there is an issue.
That could explain why 't
' might be nil.
In general, the best practice is to never ignore error.
Here:
var t *Template
if t, err := template.ParseFiles("web.html"); err != nil {
// do something
// return err
// or
// panic(err)
}
答案2
得分: 2
另一种解决方案是使用template.Must
函数,在出现错误时引发 panic。在这种情况下,使用它是合理的,因为程序需要它的资源。
t := template.Must(template.ParseFiles("web.html"))
英文:
Another solution is to use template.Must
function to cause a panic in case of error. Its usage is justified in this case because the program needs its resources.
t := template.Must(template.ParseFiles("web.html"))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论