I’m making a simple web server that writes all tcp packets recieved to output.txt, so I wrote this:
func handleRequest(conn net.Conn) {
// Make a buffer to hold incoming data.
buf := make([]byte, 1024)
// Read the incoming connection into the buffer.
size, err := conn.Read(buf)
if err != nil {
fmt.Println(“Error reading:”, err.Error())
}
s := string(buf[:size])
fmt.Println(s)
perm := os.FileMode(0644)
err = ioutil.WriteFile(“output.txt”, buf[:size], perm)
check(err)
// Close the connection when you’re done with it.
conn.Close()
}
It makes output.txt, but writes nothing in it. All the “server part” works fine(it outputs s correctly)
Does check create any output? I can’t find the definition of it in your code…
Also this board uses markdown style code formatting, so you have to either indent your code by 4 spaces or wrap it into triple-backticks with optional language annotation:
```go
// your code goes here
```
BBcode doesn’t work here.
Besides of the question with the error checking and the markdown, I see some problems with your code:
It will probably fail when you receive more than 1024 bytes at once, or at least it might not consume them properly.
You are closing a connection that might still get used on the call side.
But what about your check function? As what I can see from your code, it looks like you will continue with reporting success even when there was an error during write, that’s why I want to see your check function.
edit
Even though you say that you data will not exceed 1kByte, it might get handed over to you in a chunked mannor. You should therefore define specify a clear protocol that adheres to those circumstances.
Also I am still the opinion, that closing the connection is dangerous. The might be used from the caller after you closed it or get closed again.
And does it panic or does it run through? (remember that panics go on stderr and depending on how you run your programm might be logged into a different file or not appear at all!)
Have you tried logging before and after closing the connection?
Does it work when you replace ioutil.WriteFile with direct calls to os.Open, io.Write etc?
Logging after writing and error checking is not a question of if it works then, but a question of if the code is reached.
Please try to create a single go file with a mainpackage that reproduces your problem. Preferable is of course a repro that does not involve networking.
I can’t
When i copy and paste the code, assigning buf manually(the assignment of buf in the server app is fine, since it transforms to s correctly) it works fine
by string I mean what was in buf[:size] the question was: why don’t i see it with “cat output.txt” but can with “cat output.txt | xdd”?
And can I open it with another program(in C, for example)