代码如下:
/config/config.go
var TemplateArgs = make(map[string]interface{})
/main.go
func init() {
config.TemplateArgs["template_host"] = "http://localhost:" + config.SERVER_PORT + "/"
}
/model/model.go
type File struct {
Name string `json:"name"`
Ext string `json:"ext"`
RelativePath string `json:"relative_path"`
}
type TextFile struct {
File File
Content string `json:"content"`
}
func showTextFile(w http.ResponseWriter, file *File) {
config.TemplateArgs["file"] = TextFile{File: *file, Content: ""}
fileInfo, err := os.Stat(file.RelativePath + file.Name)
if err != nil {
log.Println("获取文件信息出错:", err.Error())
}
if fileInfo.Size() <= 0 || fileInfo.Size() > 1024*10 {
log.Printf("文件大小 %s 过大,打不开\n", fileInfo.Size())
}
fp, _ := os.Open(file.RelativePath + file.Name)
content, _ := ioutil.ReadAll(fp)
//下面这一行代码会报错
config.TemplateArgs["file"].(TextFile).Content = string(content)
t1, err := template.ParseFiles("template/show_text_file.html")
if err != nil {
panic(err)
}
_ = t1.Execute(w, config.TemplateArgs)
}
上面的代码,会出问题那里我特意标明了,好像断言有问题,我现在直接执行
go run main.go
会报错如下:
model/model.go:109:49: cannot assign to config.TemplateArgs["file"].(TextFile).Content
note: module requires Go 1.17
请高手指点一二,小弟感激涕零!
这样重新赋值、
你也可以赋值是指针 这样指针是可以重新赋值的