I've run into some difficulty when building a simple TCP based chat application in Go. My problem is that after changing the variable name, the formatting seems to go haywire and the text of the message overrides the name of the sender and other characters.
All code snippets below are taken from the server.
type Message struct {
sender *User
message string
}
type User struct {
connection net.Conn
queue chan string//Simply a queue of messages that will be sent to the client, out of the scope of this question
name string
}
Code that sets the name: (assuming the command comes in the form "/nick NAME")
command := message.message[1:]
if(strings.HasPrefix(command, "nick")) {
message.sender.name = command[5:]
fmt.Println("Set name to: " + message.sender.name)
}
Code that prints the value (note that the error persists if I concatenate the strings using the traditional s1 + s2
):
var buffer bytes.Buffer
buffer.WriteString("<")
buffer.WriteString(message.sender.name)
buffer.WriteString("> ")
buffer.WriteString(message.message)
fmt.Println(buffer.String())
sendMessage(buffer.String())
Output (server on left, client on right. Not that I send the message 'Test' both times):
As seen above, the format of the message should have been <NewName123> Test
, however the greater than symbol is misplaced and the message test can be seen overriding the name of the user. I'm stumped as to what is causing this problem.
The application works as follows: Client connects. Client sends a message, the server reads the message and applies formatting (IE add username in). Server redistributes the message to ALL users (including the sender). The clients display the message.
Any help would be fantastic.