【问题标题】:How to display HTML string as a web page using Golang http.ResponseWriter?如何使用 Golang http.ResponseWriter 将 HTML 字符串显示为网页?
【发布时间】:2016-11-01 19:51:10
【问题描述】:

我正在遵循 The Way to Go 中第 19 章中的示例。

这是我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 版本是 go version go1.6.2 linux/amd64,我认为这本书是在 2012 年用旧版本的 go 写的。

如何修改它以使其在浏览器中呈现为表单?谢谢。

【问题讨论】:

  • AddForm 不是一个完整的 html 页面,它只是表单片段。另外,您将返回Content-Type: text/plain。这个例子还有更多吗?这永远不会与 Go 标准库一起工作。
  • 这本书是here,在第517页阅读。还有一些其他的代码,但绝对与这里的html渲染无关。代码为here,在zip文件中,在chapter19/goto_v1/main.go

标签: http go


【解决方案1】:

阅读文档后,在当前版本的 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
}

【讨论】:

    【解决方案2】:

    如果您使用 HTML 模板,那就更好了。模板也会检查您的 HTML 是否有错误。

    https://play.golang.org/p/l9bUoWC4PZ

    如果在我的示例中使用 w instaed of stdout,则在 Execute 中将自动设置内容类型

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-24
      • 2016-09-06
      • 2014-02-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多