good morning!!!!

Skip to content
Snippets Groups Projects
example_test.go 2.22 KiB
Newer Older
package websocket_test

import (
	"context"
	"log"
	"net/http"
	"time"

	"nhooyr.io/websocket"
	"nhooyr.io/websocket/wsjson"
)

// This example accepts a WebSocket connection, reads a single JSON
// message from the client and then closes the connection.
func ExampleAccept() {
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, websocket.AcceptOptions{})
		if err != nil {
			log.Println(err)
			return
		}
		defer c.Close(websocket.StatusInternalError, "the sky is falling")

		ctx, cancel := context.WithTimeout(r.Context(), time.Second*10)
		defer cancel()

		var v interface{}
		err = wsjson.Read(ctx, c, &v)
		if err != nil {
			log.Println(err)
			return
		}

		log.Printf("received: %v", v)

		c.Close(websocket.StatusNormalClosure, "")
Anmol Sethi's avatar
Anmol Sethi committed
	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
// This example dials a server, writes a single JSON message and then
// closes the connection.
func ExampleDial() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()

	c, _, err := websocket.Dial(ctx, "ws://localhost:8080", websocket.DialOptions{})
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		log.Fatal(err)
	}
	defer c.Close(websocket.StatusInternalError, "the sky is falling")

	err = wsjson.Write(ctx, c, "hi")
	if err != nil {
Anmol Sethi's avatar
Anmol Sethi committed
		log.Fatal(err)
	c.Close(websocket.StatusNormalClosure, "")
Anmol Sethi's avatar
Anmol Sethi committed
// This example shows how to correctly handle a WebSocket connection
// on which you will only write and do not expect to read data messages.
func Example_writeOnly() {
Anmol Sethi's avatar
Anmol Sethi committed
	fn := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		c, err := websocket.Accept(w, r, websocket.AcceptOptions{})
		if err != nil {
			log.Println(err)
			return
		}
		defer c.Close(websocket.StatusInternalError, "the sky is falling")

		ctx, cancel := context.WithTimeout(r.Context(), time.Minute*10)
		defer cancel()

Anmol Sethi's avatar
Anmol Sethi committed
		ctx = c.CloseRead(ctx)
Anmol Sethi's avatar
Anmol Sethi committed

		t := time.NewTicker(time.Second * 30)
		defer t.Stop()

		for {
			select {
			case <-ctx.Done():
				c.Close(websocket.StatusNormalClosure, "")
				return
			case <-t.C:
				err = wsjson.Write(ctx, c, "hi")
				if err != nil {
					log.Println(err)
					return
				}
			}
		}
	})

	err := http.ListenAndServe("localhost:8080", fn)
	log.Fatal(err)
}