如何使用Golang http.ResponseWriter将HTML字符串显示为网页?
发布时间:2020-12-16 09:24:36 所属栏目:大数据 来源:网络整理
导读:我在第19章的例子中讲述了The Way to Go. 这是我的main.go的内容 package mainimport ( "fmt" "net/http")const AddForm = `form method="POST" action="/add"URL: input type="text" name="url"input type="submit" value="Add"/form`func main() { http.Ha
我在第19章的例子中讲述了The Way to Go.
这是我的main.go的内容 package main import ( "fmt" "net/http" ) const AddForm = ` <form method="POST" action="/add"> URL: <input type="text" name="url"> <input type="submit" value="Add"> </form> ` func main() { http.HandleFunc("/add",Add) http.ListenAndServe(":8080",nil) } func Add(w http.ResponseWriter,r *http.Request) { url := r.FormValue("url") if url == "" { fmt.Fprint(w,AddForm) return } key := "Placeholder" fmt.Fprintf(w,"http://localhost:8080/%s",key) } 根据这本书及其截图,我应该看到在浏览器中呈现的有效表单.但是现在,我只能看到原始字符串. 我很新,所以我不确定自从编写示例以来语言是否已经发展了很多.我的go版本是go1.6.2 linux / amd64版本,我认为这本书是用2012年的旧版本编写的. 如何修改它以使其在浏览器中呈现为表单?谢谢. 解决方法
阅读文档后,在golang的当前版本中,http.ResponseWriter将默认的Content-type设置为text / plain,并在手动将内容类型设置为text / html后,事情按预期工作.
if url == "" { w.Header().Set("Content-Type","text/html; charset=utf-8") fmt.Fprint(w,AddForm) return } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |