I am running into a rather strange (hopefully easily fixable) problem with fmt.Printf(string)
I have a GO application that uses net.Listener() to listen for connections on port 8080.
Using a web browser, I connect to the server. When the server receives a connection, it accepts and responds with the following code (I have removed the error handling)
func main() {
socket, _ := net.Listen("tcp", ":8080")
for {
connection, _ := socket.Accept()
go handleClient(connection)
}
}
// Function called as a go routine by main after accepting a connection
func handleClient(c net.Conn) {
defer c.Close()
r := bufio.NewReader(c)
for {
// Read each header line individually
req, err := r.ReadString('
')
if err != nil && err != io.EOF {
// Call function that prints the error to the console
checkError(err)
}
// Show request headers in terminal
fmt.Print(req)
// Stop reading request headers
if len(req) <= 2 {
break
}
}
// Create generic response headers - for testing only
var headers = "HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 70
Connection: keep-alive
"
// Get current dir path
pwd, _ := os.Getwd()
// Read a file (content says "This is a test, five times"
body, err := ioutil.ReadFile(pwd + "/test.txt")
if err != nil {
checkError(err)
}
// Print to terminal
fmt.Println(headers + string(body))
// Send to client
fmt.Fprintf(c, headers + string(body))
My terminal prints out (headers + body) and shows the content EXACTLY as I want it. The headers first, followed by and then the HTML content. However, my web browser only shows:
1) This is a test
2) This is a test
3) This is a test
4) This is a tes
My terminal shows all 5 lines (browser shows 4), and the 4th line is missing its last character. Is there some form of buffer that I need to set?
Lastly, this is a school assignment and we are told not to use libraries that make doing this easier (HTTP GO Libraries for example).
Thanks for any help.
EDIT: The entire function has now been posted. Note that the last two lines print the same thing. The console shows the text exactly how I intend it to be. The print to the client breaks a certain amount of bytes. Even if I do one large line, it still stops printing at some point.
EDIT 2: I have added a line that reads a file. The file is read by my browser just fine, but I have the same problem. The content is cut off.