2016-06-29 22:09
浏览 705

如何使用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 (

const AddForm = `
<form method="POST" action="/add">
URL: <input type="text" name="url">
<input type="submit" value="Add">

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)
    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条回答 默认 最新

相关推荐 更多相似问题