Golang WebSocket 框架(golang培训)

网友投稿 1108 2022-10-13

Golang WebSocket 框架(golang培训)

Golang WebSocket 框架(golang培训)

Golang WebSocket Framework (Warning! Not maintained)

Soso-server

Additional libs

soso-client soso-auth

##Install

go get -u github.com/happierall/soso-server

##Usage

import ( "fmt" soso "github.com/happierall/soso-server" ) func main() { // Simple Use: Router := soso.Default() Router.CREATE("message", func (m *soso.Msg) { m.Success(map[string]interface{}{ "id": 1, }) }) Router.Run(4000) }

// Add routes as list: var Routes = soso.Routes{} Routes.CREATE("user", UserCreate) // Handler: func UserCreate(m *soso.Msg) { type Data struct { ID int64 `json:"id"` } data := &Data{} m.ReadData(data) // Send direct message: soso.SendMsg("notify", "created", m.Session, map[string]interface{}{ "text": "Congratulation for first message", }, ) m.Success(map[string]interface{}{ "id": data.ID, }) } Router := soso.Default() Router.HandleRoutes(Routes) // You can handle net/http handlers http.HandleFunc("/oauth/callback/github", callbackGithub) // And run Router.Run(4000)

// Custom listener:Router := soso.Default()Router.Handle("user", "create", func (m *soso.Msg) {})http.HandleFunc("/soso", Router.Receiver)http.ListenAndServe("localhost:4000", nil)

Client request (if use without soso-client)

// javascript pure: var sock = new WebSocket("ws://localhost:4000/soso") var data = { model: "message", action: "create", data: {msg: "hello world"}, log: {}, other: {}, } sock.onopen = () => { sock.send( JSON.stringify( data ) ) }

Middleware and Auth

import ( soso "github.com/happierall/soso-server" jose "github.com/dvsekhvalnov/jose2go")func main() { Router := soso.Default() Router.Middleware.Before(func (m *soso.Msg, start time.Time) { token, uid, err := readToken(m) // User is blank, you can use it m.User.ID = strconv.FormatInt(uid, 10) m.User.Token = token m.User.IsAuth = true m.User.IsAnonymous = true }) Router.SEARCH("user", func(m *soso.Msg) { if m.User.IsAuth { fmt.Println(m.User.Token, m.User.ID) } }) Router.Run(4000)}

Events and Sessions

func main() { Router := soso.Default() soso.Sessions.OnOpen(func(session soso.Session) { fmt.Println("Client connected") }) soso.Sessions.OnClose(func(session soso.Session) { fmt.Println("Client disconnected") }) Router.Middleware.Before(func (m *soso.Msg, start time.Time) { uid := AuthUser() if m.User.IsAuth { soso.Sessions.Push(m.Session, uid)) } }) Router.Run(4000) }

License

MIT

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++11新特性(1)-long long
下一篇:EA&UML日拱一卒-活动图::CallOperationAction(续)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~