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

huangapple go评论81阅读模式
英文:

Getting a simple server to display a web page

问题

我正在编写一个简单的服务器作为一个项目,帮助我学习Go语言。以下是它的最简形式:

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)
}

它按预期工作,即当客户端连接到localhost:1234时,它发送所需的文本。但由于某种原因,我的浏览器将输出显示为文本而不是预期的HTML。我做错了什么?

英文:

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

package main

import (
	&quot;io&quot;
	&quot;net/http&quot;
)

func serve(w http.ResponseWriter, r *http.Request) {
	text := &quot;HTTP/1.1 200 OK\r\n&quot; +
	&quot;Content-Type: text/html\r\n&quot; + 
	&quot;Host: localhost:1234\r\n&quot; + 
	&quot;Connection: close\r\n&quot; + 
	&quot;\r\n&quot; + 
	&quot;&lt;!doctype html&gt;\r\n&quot; + 
	&quot;&lt;html&gt;...&lt;/html&gt;\r\n&quot;
	
	// Greet the user, ignoring their request.
	io.WriteString(w, text)
}

func main() {
	http.HandleFunc(&quot;/&quot;, serve)
	http.ListenAndServe(&quot;:1234&quot;, 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?

答案1

得分: 3

如果你在任何一个Chrome Inspector的替代工具中打开你的页面,你会看到它有以下内容:

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

这告诉你的浏览器如何解释它。你可以发送额外的头部信息来指定内容类型:w.Header().Set("Content-Type", "text/html"),或者只是删除所有的GET ...,只留下以下内容:

text := "<h1>页面</h1><span>页面2</span>"
英文:

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(&quot;Content-Type&quot;, &quot;text/html&quot;) or just remove all you GET ... leaving just:

text := &quot;&lt;h1&gt;page&lt;/h1&gt;&lt;span&gt;page2&lt;/span&gt;&quot;

答案2

得分: 1

在写入响应之前,您需要在ResponseWriter中设置正确的Content-Type头部。您不需要发送HTTP头部,因为在第一次调用Write时会隐式发送,或者通过WriterHeader显式发送。

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

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(&quot;Content-Type&quot;, &quot;text/html; charset=utf-8&quot;)

huangapple
  • 本文由 发表于 2015年11月24日 06:24:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/33881867.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定