douren1928 2016-06-29 22:09
浏览 722
已采纳

如何使用Golang http.ResponseWriter将HTML字符串显示为网页?

I'm following along the example in Chapter 19 from The Way to Go.

This is the content of my 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)
}

According to the book and its screenshot, I should see a valid form rendered in my browser. But right now, I can only see the raw string.

I'm very new to go, so I'm not sure if the language has evolved a lot since the example was written. My go version is go version go1.6.2 linux/amd64 and I think the book is written in 2012 with older version of go.

How do I modify it to make it render as a form in the browser? Thanks.

  • 写回答

2条回答 默认 最新

  • doulin4844 2016-06-30 01:16
    关注

    After reading through the doc, in current version of golang, http.ResponseWriter has a default Content-type as text/plain, and after manually set the content type as text/html, things are working as expected.

    if url == "" {
        w.Header().Set("Content-Type", "text/html; charset=utf-8")
        fmt.Fprint(w, AddForm)
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥20 和学习数据的传参方式,选择正确的传参方式有关
  • ¥15 这是网络安全里面的poem code
  • ¥15 用js遍历数据并对非空元素添加css样式
  • ¥15 使用autodl云训练,希望有直接运行的代码(关键词-数据集)
  • ¥50 python写segy数据出错
  • ¥20 关于线性结构的问题:希望能从头到尾完整地帮我改一下,困扰我很久了
  • ¥30 3D多模态医疗数据集-视觉问答
  • ¥20 设计一个二极管稳压值检测电路