Send exec command output as HTTP Response

Hi everyone,

I used exec.Command to call the Linux commands and send the response as http response body.

out, _ = cmd.Output()
return Response{string(out)}, nil

When I display the response with pre and code tags in my HTML page, it doesn’t show correctly.

output of exec.Command: stdout.png stdout

What showed in my web page:

  File C:\tmp
e[38;5;41m     e  should existe[0m
  File C:\tmp\AP_prod_W2k16_JP
e[38;5;41m     e  should existe[0m

I also confirmed that if copy the stdout and hard-code it as response, it shows perfectly in my web page.

str := `
  File C:\tmp
     ✔  should exist
  File C:\tmp\AP_prod_W2k16_JP
     ✔  should exist`

return Response{str}, nil

It seems to me the issue was caused by the font styling in the stdout.
My question is: how to make it show correctly in my web page in this case? Is there a way to eliminate the color/style when casting to string in Golang, or a way to preserve the style in my html page?

try running your bytes through this function to remove color codes:

func stripANSI(preoutput []byte) []byte {
    const ansi = "[\u001B\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[a-zA-Z\\d]*)*)?\u0007)|(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"
    var re = regexp.MustCompile(ansi)
    return re.ReplaceAll(preoutput, []byte{})



Your code worked just like a charm!! Thank you!

You are very welcome!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.