Why and when would a ResponseWriter generate raw html?

后端 未结 1 1305
天涯浪人
天涯浪人 2021-01-28 08:14

I don\'t understand why the code is generating the view.html and post.html data correctly but displaying it all as raw text. I had been following the guide here and as I was bui

相关标签:
1条回答
  • 2021-01-28 09:04

    As hinted, it's because you haven't set the content type. Quoting from http.ResponseWriter:

    // Write writes the data to the connection as part of an HTTP reply.
    // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
    // before writing the data.  If the Header does not contain a
    // Content-Type line, Write adds a Content-Type set to the result of passing
    // the initial 512 bytes of written data to DetectContentType.
    Write([]byte) (int, error)
    

    If you don't set the content type yourself, first call to ResponseWriter.Write() will call http.DetectContentType() to guess what to set. If the content you send starts with "<form>", it won't be detected as HTML, but "text/plain; charset=utf-8" will be set (which "instructs" the browser to display the content as text and not try to interpret it as HTML).

    If the content would start with "<html>" for example, content type "text/html; charset=utf-8" would be set automatically and it would work without further actions.

    But don't rely on automatic detection if you know what you're sending, also it's much faster to set it yourself than to run a detection algorithm on it, so simply add this line before writing/sending any data:

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    

    And also make your post.html template a complete, valid HTML document.

    Also another piece of advice: in your code you religiously omit checking returned errors. Don't do that. The least you could do is print them on the console. You will save a lot of time for yourself if you don't omit errors.

    0 讨论(0)
提交回复
热议问题