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?
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.