0

I have created a webserver that receives POST requests, creates a txt file and prints it using the lp command.

However, those strings coming from a request that contains "\n" are saved into the file with \n as a text instead of creating a line break.

If I declare a hard-coding string, the line breaks are created.

This is the relevant code:

func handler(w http.ResponseWriter, r *http.Request) {
    bodyBuffer, _ := ioutil.ReadAll(r.Body)
    err := ioutil.WriteFile("/tmp/print.txt", bodyBuffer, 0644)
    //... More code
}

If I run this command:

curl -X POST --data "My\nName" http://127.0.0.1:8080/

The text file generated contains: My\nName instead of two lines.

grouser
  • 618
  • 8
  • 23
  • 4
    This has nothing to do with Go. It's how you invoke your handler, via `curl`, and how you pass arguments to `curl`. Possible duplicate of [How to send line break with curl?](https://stackoverflow.com/questions/3872427/how-to-send-line-break-with-curl) – icza Nov 20 '18 at 13:14
  • You are right. I have used curl -X POST --data $'My\nName' http://127.0.0.1:8080/ instead and the line-breaks are created. Many thanks. – grouser Nov 20 '18 at 13:21

2 Answers2

4

"My\nName" does not interpolate \n to a newline

echo "My\nName"
My\nName

However there are ways of doing this in the shell

echo "$(printf 'My\nName')"
My
Name

Your Go is fine, the curl bash side is not behaving as expected

Vorsprung
  • 32,923
  • 5
  • 39
  • 63
0

Use curl -X POST --data $'My\nName' http://127.0.0.1:8080/ instead. $-strings (in Bash) is ANSI-C quoting which supports all C-like escape sequences including "\n".

crazyh
  • 325
  • 2
  • 10