From 540d3c2c6b00c25669328505af930d3234e8b46f Mon Sep 17 00:00:00 2001 From: Kai <494931023@qq.com> Date: Mon, 13 May 2019 04:55:25 +0800 Subject: [PATCH] feat(api): support utf8 output in websocket endpoints * change TCPConnToWebsocketConn read function to ReadRune * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Update websocket_exec.go * Delete Project_Default.xml * Delete modules.xml * Delete portainer.iml * Delete vcs.xml * Delete workspace.xml * Delete exec.go * change TCPConnToWebsocketConn read function to ReadRune * Apply suggestions from code review Co-Authored-By: Anthony Lapenna * Update stream.go --- api/http/handler/websocket/stream.go | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/api/http/handler/websocket/stream.go b/api/http/handler/websocket/stream.go index 16e68f8de..850d44a4c 100644 --- a/api/http/handler/websocket/stream.go +++ b/api/http/handler/websocket/stream.go @@ -4,6 +4,7 @@ import ( "bufio" "github.com/gorilla/websocket" "net" + "unicode/utf8" ) func streamFromWebsocketConnToTCPConn(websocketConn *websocket.Conn, tcpConn net.Conn, errorChan chan error) { @@ -26,15 +27,33 @@ func streamFromTCPConnToWebsocketConn(websocketConn *websocket.Conn, br *bufio.R for { out := make([]byte, 2048) _, err := br.Read(out) + processedOutput := validString(string(out[:])) if err != nil { errorChan <- err break } - err = websocketConn.WriteMessage(websocket.TextMessage, out) + err = websocketConn.WriteMessage(websocket.TextMessage, []byte(processedOutput)) if err != nil { errorChan <- err break } } } + +func validString(s string) string { + if !utf8.ValidString(s) { + v := make([]rune, 0, len(s)) + for i, r := range s { + if r == utf8.RuneError { + _, size := utf8.DecodeRuneInString(s[i:]) + if size == 1 { + continue + } + } + v = append(v, r) + } + s = string(v) + } + return s +}