main.go.bak 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. static "github.com/gin-contrib/static"
  6. "github.com/gin-gonic/gin"
  7. "gopkg.in/olahol/melody.v1"
  8. )
  9. type Msg struct {
  10. mtype string `json:"mtype"`
  11. payload []byte `json:"payload"`
  12. }
  13. type Handler struct {
  14. MType string
  15. Callback func(ConInfo, *Msg)
  16. }
  17. type ConInfo struct {
  18. melody *melody.Melody
  19. session *melody.Session
  20. }
  21. type WSServer struct {
  22. handler map[string]*Handler
  23. gin *gin.Engine
  24. melody *melody.Melody
  25. }
  26. func NewWSServer(gin *gin.Engine, melody *melody.Melody) *WSServer {
  27. newWSServer := WSServer{handler: map[string]*Handler{}, gin: gin, melody: melody}
  28. for _, i := range newWSServer.get_default_handler() {
  29. newWSServer.register_handler(i)
  30. }
  31. return &newWSServer
  32. }
  33. func (wss *WSServer) start() {
  34. wss.gin.Use(static.Serve("/", static.LocalFile("./public", true)))
  35. wss.gin.GET("/ws", func(c *gin.Context) {
  36. fmt.Println("handling websocket")
  37. wss.melody.HandleRequest(c.Writer, c.Request)
  38. })
  39. wss.melody.HandleMessage(func(s *melody.Session, rawMsg []byte) {
  40. fmt.Println("new websocket message")
  41. msg := Msg{}
  42. err := json.Unmarshal(rawMsg, &msg)
  43. if err != nil {
  44. fmt.Println(err)
  45. return
  46. }
  47. fmt.Println("new message: ", msg.mtype)
  48. coninfo := ConInfo{melody: wss.melody, session: s}
  49. wss.handler[msg.mtype].Callback(coninfo, &msg)
  50. //m.BroadcastOthers(msg, s)
  51. })
  52. fmt.Println("starting on :5000")
  53. wss.gin.Run(":5000")
  54. }
  55. func (wss *WSServer) register_handler(newHandler *Handler) {
  56. wss.handler[newHandler.MType] = newHandler
  57. }
  58. func (wss *WSServer) get_default_handler() []*Handler {
  59. defaultHander := []*Handler{}
  60. handleJ := &Handler{MType: "J", Callback: func(coninfo ConInfo, msg *Msg) {
  61. remsg := *msg
  62. remsg.payload = []byte("default")
  63. jsonMsg, _ := json.Marshal(remsg)
  64. coninfo.session.Write(jsonMsg)
  65. }}
  66. defaultHander = append(defaultHander, handleJ)
  67. return defaultHander
  68. }
  69. func main() {
  70. gin := gin.Default()
  71. melody := melody.New()
  72. wss := NewWSServer(gin, melody)
  73. wss.start()
  74. }