英文:
Simple Web Server Implementation: GoLang
问题
我正在尝试使用Go实现一个简单的Web服务器。我期望在客户端浏览器的URL"http://127.0.0.1.12000/"上显示"Hello World"。
我尝试了以下代码,但出现了错误。
package main
import "net"
import "fmt"
import "bufio"
// import "strings"
// 仅在示例处理中需要
func main() {
fmt.Println("Launching server...")
// 监听所有接口
ln, err := net.Listen("tcp", ":12000")
if err != nil {
fmt.Println("Launching error1...")
return
}
// 永久运行循环(或直到按下Ctrl-C)
for {
// 在端口上接受连接
conn, err := ln.Accept()
if err != nil {
fmt.Println("Launching error2...")
return
}
// 监听以换行符(\n)结尾的消息
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Println("Launching error3...")
newmessage := "Hello World!"
conn.Write([]byte(newmessage + "\n"))
return
}
// 输出接收到的消息
fmt.Print("Message Received:", string(message))
// 接收到字符串的示例处理
newmessage := "Hello World!"
conn.Write([]byte(newmessage + "\n"))
}
}
当我尝试执行该代码时,命令行显示如下内容,但浏览器上没有输出。
Launching server...
Message Received:GET / HTTP/1.1
Message Received:GET / HTTP/1.1
我是否漏掉了什么?我犯了什么错误?
英文:
I am trying to implement a simple web server using Go. I expected "Hello World" to be displayed on the client's browser at the URL "http://127.0.0.1.12000/".
I have tried the following code but ended up with errors.
package main
import "net"
import "fmt"
import "bufio"
// import "strings"
// only needed below for sample processing
func main() {
fmt.Println("Launching server...")
// listen on all interfaces
ln, err := net.Listen("tcp", ":12000")
if err != nil {
fmt.Println("Launching error1...")
return
}
// run loop forever (or until ctrl-c)
for {
// accept connection on port
conn, err := ln.Accept()
if err != nil {
fmt.Println("Launching error2...")
return
}
// will listen for message to process ending in newline (\n)
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Println("Launching error3...")
newmessage := "Hello World!"
conn.Write([]byte(newmessage + "\n"))
return
}
// output message received
fmt.Print("Message Received:", string(message))
// sample process for string received
newmessage := "Hello World!"
conn.Write([]byte(newmessage + "\n"))
}
}
When I tried to execute the code, the command line shows the following, but there is no output on browser..
Launching server...
Message Received:GET / HTTP/1.1
Message Received:GET / HTTP/1.1
Am I missing anything? Did I make any mistakes?
答案1
得分: 2
只是在这里补充一些信息...你正在编写的不是一个简单的服务器。你正在尝试编写一个没有使用net/http
包的HTTP服务器。这是非常复杂的。也许你想要一个回显服务器?
你的浏览器需要一个格式正确的HTTP响应。这意味着你不能只是向连接写入一个随机字符串,并期望它知道该怎么处理。这里有一个指向HTTP协议描述的wikipedia链接(我不打算在一个SO回答中描述整个协议)。
如果你只想要一个最基本的可以工作的答案:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8;
Content-Length: BODY的长度
BODY
注意,头部字段使用\r\n
分隔,最后一个头部字段后面有两个\r\n
。
所以,代码应该是这样的:
conn.Write([]byte("HTTP/1.1 200 OK\r\n"))
conn.Write([]byte("Content-Type: text/plain; charset=UTF-8\r\n"))
newmessage := "Hello World!"
conn.Write([]byte("Content-Length: " + strconv.Itoa(len(newmessage)) + "\r\n\r\n"))
conn.Write([]byte(newmessage + "\n"))
另外,我猜由于这是一个协议问题,我也可以告诉你,典型的HTTP端口是80,备用/测试端口是8080。这只是一些额外的约定,供你了解。
英文:
Just to add some information here.. That that isn't a simple server that you're writing. You're trying to write an HTTP server without the net/http
package. This is nontrivial. Perhaps you want an echo server instead?
Your browser wants a properly formatted HTTP response. That means you can't just write a random string to the connection and expect it to know what to do with it. Here is a wikipedia to the HTTP protocol description (I don't intend to describe an entire protocol in a SO answer).
If you want just a bare bones answer that should work:
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8;
Content-Length: LENGTH OF BODY HERE
BODY
Note that headers are separated by \r\n
and the last header is followed by two: \r\n\r\n
.
So this:
conn.Write([]byte("HTTP/1.1 200 OK\r\n"))
conn.Write([]byte("Content-Type: text/plain; charset=UTF-8\r\n"))
newmessage := "Hello World!"
conn.Write([]byte("Content-Length: " + strconv.Itoa(len(newmessage)) + "\r\n\r\n"))
conn.Write([]byte(newmessage + "\n"))
Also, I guess since this is a protocol issue I could also let you know that the typical HTTP port is 80 and the alternative/testing one is 8080. Just some added convention for your knowledge I guess.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论