Trim newline in a golang tcp server

I'm trying to figure out how to remove the new line in a golang string message that I've received from a netcat tcp message. I've used the string.TrimSpace function but I still can't seem to remove the newline. Any ideas? I've also tried to use the other trimming functions in the string package but couldn't get those to work either.

Could it be related to the error reading: EOF msg?

>>> go run newline_ex.go
Listening on localhost:8080
Error reading: EOF
received message: sometext|\n
post trim: sometext|\n

# Seperate terminal
>>> echo -n "sometext\n" | nc localhost 8080  
package main

import (
    "bufio"
    "fmt"
    "net"
    "os"
    "strings"
)

const (
    host     = "localhost"
    port     = "8080"
    adress   = host + ":" + port
    connType = "tcp"
)

func handleMsg(message string) (string, error) {
    fmt.Printf("received message: %s\n", message)
    m := strings.TrimSpace(message)
    fmt.Printf("post trim: %s \n", m)

    return "OK", nil
}

func handleRequest(conn net.Conn) {
    msg, err := bufio.NewReader(conn).ReadString('\n')
    if err != nil {
        fmt.Println("Error reading:", err.Error())
    }

    response, err := handleMsg(msg)
    if err != nil {
        fmt.Printf("fail to handle message: %v\n", err)
    }

    fmt.Printf("Sending response: %v\n", response)
    conn.Write([]byte(response + "\n"))
    conn.Close()
}

func main() {
    l, err := net.Listen(connType, adress)
    if err != nil {
        fmt.Printf("Error listening: %v", err)
        os.Exit(1)
    }
    defer l.Close()
    fmt.Println("Listening on " + adress)

    for {
        conn, err := l.Accept()
        if err != nil {
            fmt.Printf("Error accepting: %v\n", err)
            os.Exit(1)
        }

        go handleRequest(conn)
    }
}

1 answer

  • answered 2018-11-08 00:29 Pie 'Oh' Pah

    strings.Trimspace trims the leading and trailing whitespace. Use

    strings.TrimRight("sometext\n", "\n")