Best Testkube code snippet using websocket.Kind
socket.go
Source:socket.go
...46 msgDelay = 10 * time.Millisecond47)48// Message is the wire format for the websocket connection to the browser.49// It is used for both sending output messages and receiving commands, as50// distinguished by the Kind field.51type Message struct {52 Id string // client-provided unique id for the process53 Kind string // in: "run", "kill" out: "stdout", "stderr", "end"54 Body string55 Options *Options `json:",omitempty"`56}57// Options specify additional message options.58type Options struct {59 Race bool // use -race flag when building code (for "run" only)60}61// NewHandler returns a websocket server which checks the origin of requests.62func NewHandler(origin *url.URL) websocket.Server {63 return websocket.Server{64 Config: websocket.Config{Origin: origin},65 Handshake: handshake,66 Handler: websocket.Handler(socketHandler),67 }68}69// handshake checks the origin of a request during the websocket handshake.70func handshake(c *websocket.Config, req *http.Request) error {71 o, err := websocket.Origin(c, req)72 if err != nil {73 log.Println("bad websocket origin:", err)74 return websocket.ErrBadWebSocketOrigin75 }76 _, port, err := net.SplitHostPort(c.Origin.Host)77 if err != nil {78 log.Println("bad websocket origin:", err)79 return websocket.ErrBadWebSocketOrigin80 }81 ok := c.Origin.Scheme == o.Scheme && (c.Origin.Host == o.Host || c.Origin.Host == net.JoinHostPort(o.Host, port))82 if !ok {83 log.Println("bad websocket origin:", o)84 return websocket.ErrBadWebSocketOrigin85 }86 log.Println("accepting connection from:", req.RemoteAddr)87 return nil88}89// socketHandler handles the websocket connection for a given present session.90// It handles transcoding Messages to and from JSON format, and starting91// and killing processes.92func socketHandler(c *websocket.Conn) {93 in, out := make(chan *Message), make(chan *Message)94 errc := make(chan error, 1)95 // Decode messages from client and send to the in channel.96 go func() {97 dec := json.NewDecoder(c)98 for {99 var m Message100 if err := dec.Decode(&m); err != nil {101 errc <- err102 return103 }104 in <- &m105 }106 }()107 // Receive messages from the out channel and encode to the client.108 go func() {109 enc := json.NewEncoder(c)110 for m := range out {111 if err := enc.Encode(m); err != nil {112 errc <- err113 return114 }115 }116 }()117 defer close(out)118 // Start and kill processes and handle errors.119 proc := make(map[string]*process)120 for {121 select {122 case m := <-in:123 switch m.Kind {124 case "run":125 log.Println("running snippet from:", c.Request().RemoteAddr)126 proc[m.Id].Kill()127 proc[m.Id] = startProcess(m.Id, m.Body, out, m.Options)128 case "kill":129 proc[m.Id].Kill()130 }131 case err := <-errc:132 if err != io.EOF {133 // A encode or decode has failed; bail.134 log.Println(err)135 }136 // Shut down any running processes.137 for _, p := range proc {138 p.Kill()139 }140 return141 }142 }143}144// process represents a running process.145type process struct {146 out chan<- *Message147 done chan struct{} // closed when wait completes148 run *exec.Cmd149 path string150}151// startProcess builds and runs the given program, sending its output152// and end event as Messages on the provided channel.153func startProcess(id, body string, dest chan<- *Message, opt *Options) *process {154 var (155 done = make(chan struct{})156 out = make(chan *Message)157 p = &process{out: out, done: done}158 )159 go func() {160 defer close(done)161 for m := range buffer(limiter(out, p), time.After) {162 m.Id = id163 dest <- m164 }165 }()166 var err error167 if path, args := shebang(body); path != "" {168 if RunScripts {169 err = p.startProcess(path, args, body)170 } else {171 err = errors.New("script execution is not allowed")172 }173 } else {174 err = p.start(body, opt)175 }176 if err != nil {177 p.end(err)178 return nil179 }180 go func() {181 p.end(p.run.Wait())182 }()183 return p184}185// end sends an "end" message to the client, containing the process id and the186// given error value. It also removes the binary, if present.187func (p *process) end(err error) {188 if p.path != "" {189 defer os.RemoveAll(p.path)190 }191 m := &Message{Kind: "end"}192 if err != nil {193 m.Body = err.Error()194 }195 p.out <- m196 close(p.out)197}198// A killer provides a mechanism to terminate a process.199// The Kill method returns only once the process has exited.200type killer interface {201 Kill()202}203// limiter returns a channel that wraps the given channel.204// It receives Messages from the given channel and sends them to the returned205// channel until it passes msgLimit messages, at which point it will kill the206// process and pass only the "end" message.207// When the given channel is closed, or when the "end" message is received,208// it closes the returned channel.209func limiter(in <-chan *Message, p killer) <-chan *Message {210 out := make(chan *Message)211 go func() {212 defer close(out)213 n := 0214 for m := range in {215 switch {216 case n < msgLimit || m.Kind == "end":217 out <- m218 if m.Kind == "end" {219 return220 }221 case n == msgLimit:222 // Kill in a goroutine as Kill will not return223 // until the process' output has been224 // processed, and we're doing that in this loop.225 go p.Kill()226 default:227 continue // don't increment228 }229 n++230 }231 }()232 return out233}234// buffer returns a channel that wraps the given channel. It receives messages235// from the given channel and sends them to the returned channel.236// Message bodies are gathered over the period msgDelay and coalesced into a237// single Message before they are passed on. Messages of the same kind are238// coalesced; when a message of a different kind is received, any buffered239// messages are flushed. When the given channel is closed, buffer flushes the240// remaining buffered messages and closes the returned channel.241// The timeAfter func should be time.After. It exists for testing.242func buffer(in <-chan *Message, timeAfter func(time.Duration) <-chan time.Time) <-chan *Message {243 out := make(chan *Message)244 go func() {245 defer close(out)246 var (247 tc <-chan time.Time248 buf []byte249 kind string250 flush = func() {251 if len(buf) == 0 {252 return253 }254 out <- &Message{Kind: kind, Body: safeString(buf)}255 buf = buf[:0] // recycle buffer256 kind = ""257 }258 )259 for {260 select {261 case m, ok := <-in:262 if !ok {263 flush()264 return265 }266 if m.Kind == "end" {267 flush()268 out <- m269 return270 }271 if kind != m.Kind {272 flush()273 kind = m.Kind274 if tc == nil {275 tc = timeAfter(msgDelay)276 }277 }278 buf = append(buf, m.Body...)279 case <-tc:280 flush()281 tc = nil282 }283 }284 }()285 return out286}287// Kill stops the process if it is running and waits for it to exit.288func (p *process) Kill() {289 if p == nil || p.run == nil {290 return291 }292 p.run.Process.Kill()293 <-p.done // block until process exits294}295// shebang looks for a shebang ('#!') at the beginning of the passed string.296// If found, it returns the path and args after the shebang.297// args includes the command as args[0].298func shebang(body string) (path string, args []string) {299 body = strings.TrimSpace(body)300 if !strings.HasPrefix(body, "#!") {301 return "", nil302 }303 if i := strings.Index(body, "\n"); i >= 0 {304 body = body[:i]305 }306 fs := strings.Fields(body[2:])307 return fs[0], fs308}309// startProcess starts a given program given its path and passing the given body310// to the command standard input.311func (p *process) startProcess(path string, args []string, body string) error {312 cmd := &exec.Cmd{313 Path: path,314 Args: args,315 Stdin: strings.NewReader(body),316 Stdout: &messageWriter{kind: "stdout", out: p.out},317 Stderr: &messageWriter{kind: "stderr", out: p.out},318 }319 if err := cmd.Start(); err != nil {320 return err321 }322 p.run = cmd323 return nil324}325// start builds and starts the given program, sending its output to p.out,326// and stores the running *exec.Cmd in the run field.327func (p *process) start(body string, opt *Options) error {328 // We "go build" and then exec the binary so that the329 // resultant *exec.Cmd is a handle to the user's program330 // (rather than the go tool process).331 // This makes Kill work.332 path, err := ioutil.TempDir("", "present-")333 if err != nil {334 return err335 }336 p.path = path // to be removed by p.end337 out := "prog"338 if runtime.GOOS == "windows" {339 out = "prog.exe"340 }341 bin := filepath.Join(path, out)342 // write body to x.go files343 a := txtar.Parse([]byte(body))344 if len(a.Comment) != 0 {345 a.Files = append(a.Files, txtar.File{Name: "prog.go", Data: a.Comment})346 a.Comment = nil347 }348 hasModfile := false349 for _, f := range a.Files {350 err = ioutil.WriteFile(filepath.Join(path, f.Name), f.Data, 0666)351 if err != nil {352 return err353 }354 if f.Name == "go.mod" {355 hasModfile = true356 }357 }358 // build x.go, creating x359 args := []string{"go", "build", "-tags", "OMIT"}360 if opt != nil && opt.Race {361 p.out <- &Message{362 Kind: "stderr",363 Body: "Running with race detector.\n",364 }365 args = append(args, "-race")366 }367 args = append(args, "-o", bin)368 cmd := p.cmd(path, args...)369 if !hasModfile {370 cmd.Env = append(cmd.Env, "GO111MODULE=off")371 }372 cmd.Stdout = cmd.Stderr // send compiler output to stderr373 if err := cmd.Run(); err != nil {374 return err375 }376 // run x377 if isNacl() {378 cmd, err = p.naclCmd(bin)379 if err != nil {380 return err381 }382 } else {383 cmd = p.cmd("", bin)384 }385 if opt != nil && opt.Race {386 cmd.Env = append(cmd.Env, "GOMAXPROCS=2")387 }388 if err := cmd.Start(); err != nil {389 // If we failed to exec, that might be because they built390 // a non-main package instead of an executable.391 // Check and report that.392 if name, err := packageName(body); err == nil && name != "main" {393 return errors.New(`executable programs must use "package main"`)394 }395 return err396 }397 p.run = cmd398 return nil399}400// cmd builds an *exec.Cmd that writes its standard output and error to the401// process' output channel.402func (p *process) cmd(dir string, args ...string) *exec.Cmd {403 cmd := exec.Command(args[0], args[1:]...)404 cmd.Dir = dir405 cmd.Env = Environ()406 cmd.Stdout = &messageWriter{kind: "stdout", out: p.out}407 cmd.Stderr = &messageWriter{kind: "stderr", out: p.out}408 return cmd409}410func isNacl() bool {411 for _, v := range append(Environ(), os.Environ()...) {412 if v == "GOOS=nacl" {413 return true414 }415 }416 return false417}418// naclCmd returns an *exec.Cmd that executes bin under native client.419func (p *process) naclCmd(bin string) (*exec.Cmd, error) {420 pwd, err := os.Getwd()421 if err != nil {422 return nil, err423 }424 var args []string425 env := []string{426 "NACLENV_GOOS=" + runtime.GOOS,427 "NACLENV_GOROOT=/go",428 "NACLENV_NACLPWD=" + strings.Replace(pwd, runtime.GOROOT(), "/go", 1),429 }430 switch runtime.GOARCH {431 case "amd64":432 env = append(env, "NACLENV_GOARCH=amd64p32")433 args = []string{"sel_ldr_x86_64"}434 case "386":435 env = append(env, "NACLENV_GOARCH=386")436 args = []string{"sel_ldr_x86_32"}437 case "arm":438 env = append(env, "NACLENV_GOARCH=arm")439 selLdr, err := exec.LookPath("sel_ldr_arm")440 if err != nil {441 return nil, err442 }443 args = []string{"nacl_helper_bootstrap_arm", selLdr, "--reserved_at_zero=0xXXXXXXXXXXXXXXXX"}444 default:445 return nil, errors.New("native client does not support GOARCH=" + runtime.GOARCH)446 }447 cmd := p.cmd("", append(args, "-l", "/dev/null", "-S", "-e", bin)...)448 cmd.Env = append(cmd.Env, env...)449 return cmd, nil450}451func packageName(body string) (string, error) {452 f, err := parser.ParseFile(token.NewFileSet(), "prog.go",453 strings.NewReader(body), parser.PackageClauseOnly)454 if err != nil {455 return "", err456 }457 return f.Name.String(), nil458}459// messageWriter is an io.Writer that converts all writes to Message sends on460// the out channel with the specified id and kind.461type messageWriter struct {462 kind string463 out chan<- *Message464}465func (w *messageWriter) Write(b []byte) (n int, err error) {466 w.out <- &Message{Kind: w.kind, Body: safeString(b)}467 return len(b), nil468}469// safeString returns b as a valid UTF-8 string.470func safeString(b []byte) string {471 if utf8.Valid(b) {472 return string(b)473 }474 var buf bytes.Buffer475 for len(b) > 0 {476 r, size := utf8.DecodeRune(b)477 b = b[size:]478 buf.WriteRune(r)479 }480 return buf.String()...
Kind
Using AI Code Generation
1import (2func main() {3 fmt.Println(websocket.TextMessage)4 fmt.Println(websocket.BinaryMessage)5 fmt.Println(websocket.CloseMessage)6 fmt.Println(websocket.PingMessage)7 fmt.Println(websocket.PongMessage)8}
Kind
Using AI Code Generation
1import ( 2var upgrader = websocket.Upgrader{ 3 CheckOrigin: func(r *http.Request) bool {4 },5}6func main() { 7 http.HandleFunc(“/ws”, handleConnections)8 http.ListenAndServe(“:8080”, nil)9}10func handleConnections(w http.ResponseWriter, r *http.Request) { 11 ws, err := upgrader.Upgrade(w, r, nil)12 if err != nil {13 log.Fatal(err)14 }15 defer ws.Close()16 for {17 err := ws.ReadJSON(&msg)18 if err != nil {19 log.Printf(“error: %v”, err)20 }21 }22}23import ( 24var addr = flag.String(“addr”, “:8080”, “http service address”) 25var homeTempl = template.Must(template.ParseFiles(“home.html”))26func home(w http.ResponseWriter, r *http.Request) { 27 if r.URL.Path != “/” {28 http.Error(w, “Not found”, 404)29 }30 if r.Method != “GET” {31 http.Error(w, “Method not allowed”, 405)32 }33 homeTempl.Execute(w, r.Host)34}35func serveWs(w http.ResponseWriter, r *http.Request) { 36 conn, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(w, r, nil)37 if err != nil {38 log.Println(err)39 }40 defer conn.Close()41 for {42 _, p, err := conn.ReadMessage()43 if err != nil {44 log.Println(err)45 }46 fmt.Println(string
Kind
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error in connection")5 }6 fmt.Println("Connected")7 var msg = make([]byte, 512)8 for {9 n, err = ws.Read(msg)10 if err != nil {11 fmt.Println("Error in reading")12 }13 fmt.Println(string(msg[:n]))14 }15}16import (17var upgrader = websocket.Upgrader{}18func main() {19 http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {20 conn, err := upgrader.Upgrade(w, r, nil)21 if err != nil {22 log.Println(err)23 }24 for {25 messageType, p, err := conn.ReadMessage()26 if err != nil {27 log.Println(err)28 }29 log.Printf("Received: %s", p)30 if err := conn.WriteMessage(messageType, p); err != nil {31 log.Println(err)32 }33 }34 })35 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {36 http.ServeFile(w, r, "index.html")37 })38 http.ListenAndServe(":8080", nil)39}40import (
Kind
Using AI Code Generation
1import (2func main() {3 if err != nil {4 panic(err)5 }6 fmt.Println(ws.Config().Origin)7 fmt.Println(ws.Config().Location)8 fmt.Println(ws.Config().Protocol)9 fmt.Println(ws.Config().Version)10 fmt.Println(ws.Config().Header)11 fmt.Println(ws.Config().UserAgent())12 fmt.Println(ws.Config().Origin.Scheme)13 fmt.Println(ws.Config().Origin.Host)14 fmt.Println(ws.Config().Origin.Path)15 fmt.Println(ws.Config().Origin.RawQuery)16 fmt.Println(ws.Config().Origin.Fragment)17 fmt.Println(ws.Config().Location.Scheme)18 fmt.Println(ws.Config().Location.Host)19 fmt.Println(ws.Config().Location.Path)20 fmt.Println(ws.Config().Location.RawQuery)21 fmt.Println(ws.Config().Location.Fragment)22 fmt.Println(ws.Config().Protocol[0])23 fmt.Println(ws.Config().Version)24 fmt.Println(ws.Config().Header["User-Agent"][0])25 fmt.Println(ws.Config().Header["Origin"][0])26 fmt.Println(ws.Config().Header["Sec-WebSocket-Key"][0])27 fmt.Println(ws.Config().Header["Sec-WebSocket-Version"][0])28 fmt.Println(ws.Config().Header["Sec-WebSocket-Extensions"][0])29 fmt.Println(ws.Config().Header["Sec-WebSocket-Accept"][0])30 fmt.Println(ws.Config().Header["Upgrade"][0])31 fmt.Println(ws.Config().Header["Connection"][0])32}33permessage-deflate; client_max_window_bits
Kind
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 fmt.Println(ws.Config().Origin)7 fmt.Println(ws.Config().Location)8 fmt.Println(ws.Config().Protocol)9 fmt.Println(ws.Config().Header)10 fmt.Println(ws.Config().Version)11 fmt.Println(ws.Config().HandshakeTimeout)12 fmt.Println(ws.Config().TlsConfig)13 fmt.Println(ws.Config().Origin)14 fmt.Println(ws.Config().Location)15 fmt.Println(ws.Config().Protocol)16 fmt.Println(ws.Config().Header)17 fmt.Println(ws.Config().Version)18 fmt.Println(ws.Config().HandshakeTimeout)19 fmt.Println(ws.Config().TlsConfig)20}
Kind
Using AI Code Generation
1import (2type WebSocket struct {3}4func (ws WebSocket) Kind() string {5}6func main() {7 ws := WebSocket{"ws"}8 fmt.Println(ws.Kind())9}10import (11type WebSocket struct {12}13func (ws WebSocket) Kind() string {14}15func main() {16 ws := WebSocket{"ws"}17 fmt.Println(ws.Kind())18}19import (20type WebSocket struct {21}22func (ws WebSocket) Kind() string {23}24func main() {25 ws := WebSocket{"ws"}26 fmt.Println(ws.Kind())27}28import (29type WebSocket struct {30}31func (ws WebSocket) Kind() string {32}33func main() {34 ws := WebSocket{"ws"}35 fmt.Println(ws.Kind())36}37import (38type WebSocket struct {39}40func (ws WebSocket) Kind() string {41}42func main() {43 ws := WebSocket{"ws"}44 fmt.Println(ws.Kind())
Kind
Using AI Code Generation
1import (2func main() {3 fmt.Println(ws.Kind())4}5Your name to display (optional):6Your name to display (optional):7Your name to display (optional):
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!