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

时间:2014-05-28 12:09:00

标签: go

这是我的代码,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)
}

1 个答案:

答案 0 :(得分:1)

添加内容类型和<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")
}