为什么 fmt.Fprint 在页面上没有生成 HTML 输出?

huangapple go评论111阅读模式
英文:

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 (
	&quot;fmt&quot;
	&quot;net/http&quot;
)

const AddForm = `
&lt;form method==&quot;POST&quot; action=&quot;/add&quot;&gt;
URL: &lt;input type=&quot;text&quot; name=&quot;url&quot;&gt;
&lt;input type=&quot;submit&quot; value=“Add”&gt;
&lt;/form&gt;
`

func main() {
	http.HandleFunc(&quot;/add&quot;, Add)
	http.ListenAndServe(&quot;:8099&quot;, 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 &lt;body&gt; tag seems to solve the problem

package main

import (
	&quot;fmt&quot;
	&quot;net/http&quot;
)

const AddForm = `
&lt;body&gt;
&lt;form method=&quot;POST&quot; action=&quot;/add&quot;&gt;
URL: &lt;input type=&quot;text&quot; name=&quot;url&quot;&gt;
&lt;input type=&quot;submit&quot; value=“Add”&gt;
&lt;/form&gt;
&lt;/body&gt;
`

func main() {
	http.HandleFunc(&quot;/add&quot;, Add)
	http.ListenAndServe(&quot;:8099&quot;, nil)
}

func Add(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, AddForm)
	w.Header().Add(&quot;Content-Type&quot;, &quot;text/html&quot;)
}

huangapple
  • 本文由 发表于 2014年5月28日 20:09:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/23911214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定