dov6891 2015-03-26 11:42
浏览 73
已采纳

内存错误,Go中的html / template

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...

  • 写回答

2条回答 默认 最新

  • douti8321 2015-03-26 11:47
    关注

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用