douqiao5314 2015-10-23 01:07
浏览 65
已采纳

简单的Web服务器实现:GoLang

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 (
)
        message, err := bufio.NewReader(conn).ReadString('
')

        if err != nil {
            fmt.Println("Launching error3...")
            newmessage := "Hello World!"
            conn.Write([]byte(newmessage + "
"))
            return
        }

        // output message received
        fmt.Print("Message Received:", string(message))

        // sample process for string received
        newmessage := "Hello World!"
        conn.Write([]byte(newmessage + "
"))
    }
}

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条回答 默认 最新

  • dttl3933 2015-10-23 08:30
    关注

    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 and the last header is followed by two: .

    So this:

    conn.Write([]byte("HTTP/1.1 200 OK
    "))
    conn.Write([]byte("Content-Type: text/plain; charset=UTF-8
    "))
    newmessage := "Hello World!"
    conn.Write([]byte("Content-Length: " + strconv.Itoa(len(newmessage)) + "
    
    "))
    conn.Write([]byte(newmessage + "
    "))
    

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容