亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

簡單的 Web 服務器實現:GoLang

簡單的 Web 服務器實現:GoLang

Go
慕容森 2021-11-15 20:49:00
我正在嘗試使用 Go 實現一個簡單的 Web 服務器。我希望“Hello World”顯示在客戶端瀏覽器的 URL“ http://127.0.0.1.12000/ ”上。我嘗試了以下代碼,但最終出現錯誤。package mainimport "net"import "fmt"import "bufio"// import "strings"// only needed below for sample processingfunc 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"))    }}當我嘗試執行代碼時,命令行顯示以下內容,但瀏覽器上沒有輸出..Launching server...Message Received:GET / HTTP/1.1Message Received:GET / HTTP/1.1我錯過了什么嗎?我犯了什么錯誤嗎?
查看完整描述

1 回答

?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

只是在這里添加一些信息.. 那不是您正在編寫的簡單服務器。您正在嘗試編寫一個沒有net/http包的 HTTP 服務器。這是不平凡的。也許你想要一個回聲服務器?


您的瀏覽器需要格式正確的 HTTP 響應。這意味著您不能只是向連接寫入一個隨機字符串并期望它知道如何處理它。這是HTTP 協議描述的維基百科(我不打算在 SO 答案中描述整個協議)。


如果你只想要一個應該有效的簡單答案:


HTTP/1.1 200 OK

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

Content-Length: LENGTH OF BODY HERE


BODY

請注意,標頭由 分隔,\r\n最后一個標頭后跟兩個:\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。我猜只是為您的知識添加了一些約定。


查看完整回答
反對 回復 2021-11-15
  • 1 回答
  • 0 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號