英文:
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 (
"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?
答案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("Content-Type", "text/html")
or just remove all you GET ...
leaving just:
text := "<h1>page</h1><span>page2</span>"
答案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("Content-Type", "text/html; charset=utf-8")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论