在Golang TCP服务器中修剪换行符

时间:2018-11-08 00:15:57

标签: string go tcp

我试图找出如何从netcat tcp消息中收到的golang字符串消息中删除新行。我已经使用了string.TrimSpace函数,但似乎仍然无法删除换行符。有任何想法吗?我还尝试过在字符串包中使用其他修整函数,但也无法使它们正常工作。

可能与以下错误读数有关: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 个答案:

答案 0 :(得分:2)

strings.Trimspace修剪前导和尾随空格。使用

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