1 回答
TA贡献1818条经验 获得超3个赞
将我的最终代码放在这里
func serveWs(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
log.Println("create new connection")
defer func() {
conn.Close()
log.Println("connection close")
}()
logsClient, err := InitKubeLogsClient(config.InCluster)
if err != nil {
log.Println(err)
return
}
stream, err := logsClient.GetLogs(config.Namespace, config.PodName, config.ContainerName)
if err != nil {
log.Println(err)
return
}
defer stream.Close()
reader := bufio.NewReaderSize(stream, 16)
lastLine := ""
for {
data, isPrefix, err := reader.ReadLine()
if err != nil {
log.Println(err)
return
}
lines := strings.Split(string(data), "\r")
length := len(lines)
if len(lastLine) > 0 {
lines[0] = lastLine + lines[0]
lastLine = ""
}
if isPrefix {
lastLine = lines[length-1]
lines = lines[:(length - 1)]
}
for _, line := range lines {
if err := conn.WriteMessage(websocket.TextMessage, []byte(line)); err != nil {
log.Println(err)
return
}
}
}
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报