I can't access the values in an array somehow. Here is how the array is declared:
messages := strings.Split(request_string, end_of_message_terminator)
But when I make a loop over this array, I get empty strings as values. That's the loop:
for i, v := range messages {
fmt.Printf("messages are (3) %q
", messages)
go func(){
fmt.Printf("message is %s
", messages[i])
fmt.Printf("i is %s
", i)
fmt.Printf("v is %s
", v)
respond_to_message(messages[i], response_writer())
}()
}
And that's the output:
messages are (3) ["asti" ""]
messages are (3) ["asti" ""]
message is
i is %!s(int=1)
v is
message is
i is %!s(int=1)
v is
Does anyone know what the problem is? Why can I access the individual values in this slice?
Just in case you want to run this code, here is the entire program:
package main
import (
"fmt"
"net"
"os"
"strings"
// "io/ioutil"
)
func main() {
end_of_message_terminator := "||"
beginning_of_next_message := ""
request := make([]byte, 512)
service_port := ":7777"
tcpAddr, err := net.ResolveTCPAddr("tcp4", service_port)
checkError(err)
listener, err := net.ListenTCP("tcp", tcpAddr)
checkError(err)
for {
conn, err := listener.Accept()
if err != nil {
continue
}
read_len, err := conn.Read(request)
if read_len == 0 {
continue
}
request_string := string(request[:read_len])
fmt.Printf("Request String '%s'
", request_string)
messages := strings.Split(request_string, end_of_message_terminator)
fmt.Printf("messages are (1) %q
", messages)
messages[0] = beginning_of_next_message + messages[0]
if messages[len(messages) - 1] != "" {
beginning_of_next_message = messages[len(messages) - 1]
messages[len(messages) - 1] = ""
}
if len(messages) == 1 {
continue
}
fmt.Printf("messages are (2) %q
", messages)
for i, v := range messages {
fmt.Printf("messages are (3) %q
", messages)
go func(){
fmt.Printf("message is %s
", messages[i])
fmt.Printf("i is %s
", i)
fmt.Printf("v is %s
", v)
}()
}
conn.Close()
}
}
func checkError(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "Fatal error: %s", err.Error())
os.Exit(1)
}
}
You need to run this program first:
netcat -l -p 8000
And then, finally (after starting both this program and running netcat -l -p 8000
) you need to run:
printf "asti||" | netcat localhost 7777