Skip to content

Having trouble to get it work with gin-gonic/gin #180

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
master-g opened this issue Dec 11, 2019 · 2 comments
Closed

Having trouble to get it work with gin-gonic/gin #180

master-g opened this issue Dec 11, 2019 · 2 comments

Comments

@master-g
Copy link

master-g commented Dec 11, 2019

$ go version
go version go1.13.4 darwin/amd64

I'm trying to switch from gorilla/websocket to this nice lib, but having some trouble,

the serverWithGin() version will always timeout.

any help would be appreciated!

package main

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

	"github.com/gin-gonic/gin"
	"nhooyr.io/websocket"
)

func main() {
	go serveWithGin()
	// go serve()
	go client()
	select {}
}

func serve() {
	http.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) {
		conn, err := websocket.Accept(writer, request, nil)
		if err != nil {
			log.Fatal(err)
		}
		ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
		defer cancel()
		err = conn.Write(ctx, websocket.MessageText, []byte("hello"))
		if err != nil {
			log.Fatal(err)
		}
	})
	log.Fatal(http.ListenAndServe(":8100", nil))
}

func serveWithGin() {
	r := gin.Default()
	r.GET("/ws", func(c *gin.Context) {
		conn, err := websocket.Accept(c.Writer, c.Request, nil)
		if err != nil {
			log.Fatal(err)
		}
		ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
		defer cancel()
		err = conn.Write(ctx, websocket.MessageText, []byte("hello"))
		if err != nil {
			log.Fatal(err)
		}
	})
	r.Run(":8100")
}

func client() {
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()
	cli, _, err := websocket.Dial(ctx, "ws://localhost:8100/ws", nil)
	if err != nil {
		log.Fatal(err)
	}
	_, data, err := cli.Read(ctx)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("recv: %v\n", string(data))
}
@master-g
Copy link
Author

sorry, Just found #166

@nhooyr
Copy link
Contributor

nhooyr commented May 12, 2020

@master-g Should work now with gin-gonic btw.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants