douxie1692
douxie1692
2015-11-23 22:24

获取一个简单的服务器来显示网页

  • server
已采纳

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
" +
    "Content-Type: text/html
" + 
    "Host: localhost:1234
" + 
    "Connection: close
" + 
    "
" + 
    "<!doctype html>
" + 
    "<html>...</html>
"

    // 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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douxiandiyo58855 douxiandiyo58855 6年前

    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")
    
    点赞 评论 复制链接分享
  • dongtan8979 dongtan8979 6年前

    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>"
    
    点赞 评论 复制链接分享

为你推荐