英文:
why fmt.Fprint didn't generate html output on the page?
问题
这是我的代码,fmt.Fprint在页面上输出源代码而不是生成HTML输出。我做错了什么?
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(":8099", nil)
}
func Add(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, AddForm)
}
你的代码看起来没有明显的错误。但是,我注意到你在HTML表单的<form>
标签中使用了==
而不是=
来指定method
属性的值。这可能导致表单提交时出现问题。请尝试将==
更改为=
,然后重新运行代码,看看问题是否解决了。
英文:
Here's my code, fmt.Fprint outputs the source code on the page instead generates html output. What did I do wrong?
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(":8099", nil)
}
func Add(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, AddForm)
}
答案1
得分: 1
添加content-type和<body>
标签似乎解决了问题
package main
import (
"fmt"
"net/http"
)
const AddForm = `
<body>
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">
</form>
</body>
`
func main() {
http.HandleFunc("/add", Add)
http.ListenAndServe(":8099", nil)
}
func Add(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, AddForm)
w.Header().Add("Content-Type", "text/html")
}
英文:
Adding the content-type and a <body>
tag seems to solve the problem
package main
import (
"fmt"
"net/http"
)
const AddForm = `
<body>
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value=“Add”>
</form>
</body>
`
func main() {
http.HandleFunc("/add", Add)
http.ListenAndServe(":8099", nil)
}
func Add(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, AddForm)
w.Header().Add("Content-Type", "text/html")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论