16

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
  • 1
    AddForm isn't a full html page, it's just the form fragment. Plus you're returning Content-Type: text/plain. Is there more to the example? This would never have worked wit the Go std lib. Commented Jun 29, 2016 at 22:12
  • The book is here and reading at Page 517. There are some other code, but definitely unrelated to html render here. The code is here, in the zip file, in chapter19/goto_v1/main.go Commented Jun 30, 2016 at 0:23

2 Answers 2

22

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you use HTML templates it is better. Template checks your HTML for errors too.

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

In Execute if you used w instaed of stdout in my example the content type would automatically be set

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.