github.com/demisto/mattermost-server@v4.9.0-rc3+incompatible/wsapi/websocket_handler.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package wsapi
     5  
     6  import (
     7  	l4g "github.com/alecthomas/log4go"
     8  
     9  	"net/http"
    10  
    11  	"github.com/mattermost/mattermost-server/app"
    12  	"github.com/mattermost/mattermost-server/model"
    13  	"github.com/mattermost/mattermost-server/utils"
    14  )
    15  
    16  func (api *API) ApiWebSocketHandler(wh func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError)) webSocketHandler {
    17  	return webSocketHandler{api.App, wh}
    18  }
    19  
    20  type webSocketHandler struct {
    21  	app         *app.App
    22  	handlerFunc func(*model.WebSocketRequest) (map[string]interface{}, *model.AppError)
    23  }
    24  
    25  func (wh webSocketHandler) ServeWebSocket(conn *app.WebConn, r *model.WebSocketRequest) {
    26  	l4g.Debug("websocket: %s", r.Action)
    27  
    28  	session, sessionErr := wh.app.GetSession(conn.GetSessionToken())
    29  	if sessionErr != nil {
    30  		l4g.Error(utils.T("api.web_socket_handler.log.error"), "websocket", r.Action, r.Seq, conn.UserId, sessionErr.SystemMessage(utils.T), sessionErr.Error())
    31  		sessionErr.DetailedError = ""
    32  		errResp := model.NewWebSocketError(r.Seq, sessionErr)
    33  
    34  		conn.Send <- errResp
    35  		return
    36  	}
    37  
    38  	r.Session = *session
    39  	r.T = conn.T
    40  	r.Locale = conn.Locale
    41  
    42  	var data map[string]interface{}
    43  	var err *model.AppError
    44  
    45  	if data, err = wh.handlerFunc(r); err != nil {
    46  		l4g.Error(utils.T("api.web_socket_handler.log.error"), "websocket", r.Action, r.Seq, r.Session.UserId, err.SystemMessage(utils.T), err.DetailedError)
    47  		err.DetailedError = ""
    48  		errResp := model.NewWebSocketError(r.Seq, err)
    49  
    50  		conn.Send <- errResp
    51  		return
    52  	}
    53  
    54  	resp := model.NewWebSocketResponse(model.STATUS_OK, r.Seq, data)
    55  
    56  	conn.Send <- resp
    57  }
    58  
    59  func NewInvalidWebSocketParamError(action string, name string) *model.AppError {
    60  	return model.NewAppError("websocket: "+action, "api.websocket_handler.invalid_param.app_error", map[string]interface{}{"Name": name}, "", http.StatusBadRequest)
    61  }