Add websocket module for open source project go gin API

Xinliang notes 2021-10-14 07:10:58

List of articles :

  • WebSocket Sample interface

  • Third party package

  • Code encapsulation

  • Summary

  • Recommended reading

WebSocket Sample interface


Third party package

  • gorilla/websocket [1]

websocket Configuration items are supported when linking :

type Upgrader struct {
    //  Specify upgrade  websocket  Timeout for handshake completion
    HandshakeTimeout time.Duration

    //  Appoint io The cache size of the operation , If not specified, it will be automatically assigned .
    ReadBufferSize, WriteBufferSize int

    //  Cache pool for write data operations , If there is no set value ,write buffers Will be assigned to the link lifecycle .
    WriteBufferPool BufferPool

    // Specify the protocols supported by the service in order , If the value exists , The service will match the client's protocol from the first .
    Subprotocols []string

    //  Appoint http Error response function , If not set Error be , Will generate http.Error Error response to .
    Error func(w http.ResponseWriter, r *http.Request, status int, reason error)

    //  Request check function , For unified link checking , To prevent cross site request forgery . If you don't check , Set a return value to  true  Function of .
    //  If you ask for  Origin  The header can accept ,CheckOrigin  Will return  true.  If CheckOrigin by nil, Then use the security default : If Origin The request header exists and the original host is not equal to the request host header , Then return to  false
    CheckOrigin func(r *http.Request) bool

    // EnableCompression Specifies whether the server should attempt to negotiate each message compression (RFC 7692). 
    //  Set this value to true There is no guarantee that compression will be supported . 
    //  Currently only supported “ No context takeover ” Pattern
    EnableCompression bool

Upgrade Function can change http Upgrade to WebSocket agreement :

// responseHeader Included in the response to the client upgrade request . 
//  Use responseHeader Appoint cookie(Set-Cookie) Sub protocol negotiated with the application (Sec-WebSocket-Protocol).
//  If the upgrade fails , The upgrade will use  HTTP  The error response replies to the client
//  Return to one Conn The pointer , When you get him , You can use Conn Read and write data and communicate with the client .
func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error)

Code encapsulation

Encapsulates a socket_server, It also supports the use of logs 、 database 、 Cache and other operations :

type Server interface {

 // OnMessage  receive messages

 // OnSend  Send a message
 OnSend(message []byte) error

 // OnClose  close

func New(logger *zap.Logger, db db.Repo, cache cache.Repo, conn *websocket.Conn) (Server, error) {

Encapsulates a socket_conn

func (h *handler) Connect() core.HandlerFunc {
 var upGrader = websocket.Upgrader{
  HandshakeTimeout: 5 * time.Second,
  CheckOrigin: func(r *http.Request) bool {
   return true

 return func(ctx core.Context) {
  ws, err := upGrader.Upgrade(ctx.ResponseWriter(), ctx.Request(), nil)
  if err != nil {

  server, err = socket_server.New(h.logger, h.db, h.cache, ws)
  if err != nil {

  go server.OnMessage()

socket_conn It's a HandlerFunc, It can be used directly in routing .

In the project websocket The link address is :/socket/system/message, The interface for sending messages is :/api/tool/send_message.

JavaScript Sample code :

const ws = new WebSocket("ws://");

// Triggered when the connection is open
ws.onopen = function (evt) {

// Trigger when a message is received
ws.onmessage = function (evt) {

// Triggered when the connection is closed
ws.onclose = function (evt) {

In the project Utility toolbox -> WebSocket Interface , The right side requests the interface to send a message , Messages can be received in real time on the left .


This article is just to throw a brick to attract jade , There is a problem , Welcome criticism and correction .

go-gin-api[2] The project is ready to use , Support WEB Interface one click installation , Go and have a try .

Recommended reading

Reference material





 New bright notes
New bright notes
The way to upgrade the program ape .
150 Original content
official account


Please bring the original link to reprint ,thank
Similar articles