Skip to content
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

support realtime? #1305

Open
HosseinAlipour opened this issue Apr 5, 2018 · 2 comments

Comments

@HosseinAlipour
Copy link

@HosseinAlipour HosseinAlipour commented Apr 5, 2018

I know it uses HTTP protocol but I'm wondering if somehow it is possible to make real-time API server with gin. is it possible?

@sosedoff

This comment has been minimized.

Copy link

@sosedoff sosedoff commented Apr 11, 2018

You can use https://github.com/gorilla/websocket for websocket stuff.
Check out this example:

package main

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

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	upgrader = websocket.Upgrader{
		ReadBufferSize:   1024,
		WriteBufferSize:  1024,
		CheckOrigin:      func(r *http.Request) bool { return true },
		HandshakeTimeout: time.Duration(time.Second * 5),
	}
)

func handleWebsocket(c *gin.Context) {
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println("cant upgrade connection:", err)
		return
	}

	for {
		msgType, msgData, err := conn.ReadMessage()
		if err != nil {
			log.Println("cant read message:", err)

			switch err.(type) {
			case *websocket.CloseError:
				return
			default:
				return
			}
		}

		// Skip binary messages
		if msgType != websocket.TextMessage {
			continue
		}

		log.Printf("incoming message: %s\n", msgData)
	}
}

func main() {
	router := gin.Default()
	router.GET("/websocket", handleWebsocket)
	router.Run(":5000")
}

Once the server is running, you can use something like wscat to send test messages.

@blusewang

This comment has been minimized.

Copy link

@blusewang blusewang commented Jul 30, 2019

It's awesome!
thank #sosedoff 's examle.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants
You can’t perform that action at this time.