0

I'm writing a simple server as a project to help me learn Go. Here's its minimal form:

package main

import (
    "io"
    "net/http"
)

func serve(w http.ResponseWriter, r *http.Request) {
    text := "HTTP/1.1 200 OK\r\n" +
    "Content-Type: text/html\r\n" + 
    "Host: localhost:1234\r\n" + 
    "Connection: close\r\n" + 
    "\r\n" + 
    "<!doctype html>\r\n" + 
    "<html>...</html>\r\n"

    // Greet the user, ignoring their request.
    io.WriteString(w, text)
}

func main() {
    http.HandleFunc("/", serve)
    http.ListenAndServe(":1234", nil)
}

It works as expected in terms that it sends the desired text when a client connects to localhost:1234. But for some reason my browser displays the output as text instead of HTML, as desired. What am I doing wrong?

Charles
  • 10,210
  • 13
  • 57
  • 94
  • http://stackoverflow.com/questions/12830095/setting-http-headers-in-golang – Gillespie Nov 23 '15 at 22:33
  • 1
    Keep in mind that HTTP and HTML aren't implicitly tied together. Go will try and inspect the MIME type of your content and set the Content-Type header appropriately, but in some cases it cannot do that. – elithrar Nov 23 '15 at 23:56

2 Answers2

2

If you will open your page in any alternative of chrome inspector, you will see that it has:

Content-Type:text/plain; charset=utf-8

Which tells your browser how to interpret it. You can send additional header specifying the content type: w.Header().Set("Content-Type", "text/html") or just remove all you GET ... leaving just:

text := "<h1>page</h1><span>page2</span>"
Salvador Dali
  • 182,715
  • 129
  • 638
  • 708
1

You need to set the proper Content-Type header in the ResponseWriter before you write the response. You don't need to send the HTTP header, as that's sent implicitly on the first call to Write, or explicitly via WriterHeader.

w.Header().Set("Content-Type", "text/html; charset=utf-8")
JimB
  • 87,033
  • 9
  • 198
  • 196
  • Oh I see -- Go is sending HTTP on its own, and my HTTP was passed after the actual HTTP. Thanks! – Charles Nov 23 '15 at 22:30