kubernetes attach pod use websocket

7/23/2018

I want make a web terminal by kubernetes client-go api, and now i meet some problem.

main:

func main() {
flag.Parse()
log.SetFlags(0)
http.HandleFunc("/ws", echo)
log.Fatal(http.ListenAndServe(*addr, nil))
}

struct&handleFunc:

type Cmd struct {
 Conn   *websocket.Conn
 Stdin  io.Reader
 Stdout io.Writer
 Stderr io.Writer
}



func echo(w http.ResponseWriter, r *http.Request) {
  cmd := Cmd{}
  cmd.Stderr = ioutil.Discard

  c, err := upgrader.Upgrade(w, r, nil)
  if err != nil {
    log.Print("upgrade:", err)
    return
  }
  cmd.Conn = c

  cmd.handleClient()

  }
func (c *Cmd) handleClient() {
//c.Stdout = os.Stdout
//c.Stdin = os.Stdin
var read io.Reader
var write io.Writer
c.Stdin = read
c.Stdout = write

go func(rd io.Reader) {
    for {
        _, r, err := c.Conn.NextReader()
        if err != nil {
            fmt.Println("ReadErr:", err)
            c.Conn.Close()
            return
        }
        rd = r

    }
}(read)

go func(wr io.Writer) {

    w, err := c.Conn.NextWriter(1)
    if err != nil {
        fmt.Println("WriteErr:", err)
        c.Conn.Close()
        return
    }
    wr = w

}(write)
err := api.ExecOperator{}.ExecConsoleInContainer("1", "nginx-65899c769f-mkswf", c.Stdin, c.Stdout, c.Stderr)
if err != nil {
    fmt.Println("ExecErr:", err)
    return
  }
}

api.ExecOperator{}.ExecConsoleInContainer() is a func invoke kubernetes exec api like kubernetes exec_util.go

When i use the code below,i can operate at the console,but i dont know how to use websocket(gorilla/websocket) input and output to replace os.stdin and os.stdout,i tried to write some of the code above ,but it cant work.

c.Stdout = os.Stdout
c.Stdin = os.Stdin
-- Mosesyou
docker
go
kubernetes
pod
websocket

0 Answers