Feature Request: *http.Request access from Websockets. iris.Config.Websocket.IDGenerator custom connection's ID generator added too.

Example:

-
https://github.com/iris-contrib/examples/blob/master/websocket/main.go#L34

Relative commits to kataras/go-websocket:
-
550fc8b32e

-
62c2d989d8
This commit is contained in:
Gerasimos (Makis) Maropoulos 2017-01-09 06:23:49 +02:00
parent d5d113b4ca
commit c476fe8921
5 changed files with 131 additions and 25 deletions

View File

@ -50,6 +50,8 @@ I'm grateful for all the generous donations. Iris is fully funded by these dona
- ANONYMOUS donated 5 EUR at December 13 - ANONYMOUS donated 5 EUR at December 13
- [Github username is not available yet] donated 25 EUR at Jenuary 8 of 2017
> * The name or/and github username link added after donator's approvement via e-mail. > * The name or/and github username link added after donator's approvement via e-mail.
#### Report, so far #### Report, so far
@ -58,5 +60,5 @@ I'm grateful for all the generous donations. Iris is fully funded by these dona
- **Thanks** to all of **You**, 424 EUR donated to [Holy Metropolis of Ioannina](http://www.imioanninon.gr/main/) for clothes, foods and medications for our fellow human beings. - **Thanks** to all of **You**, 424 EUR donated to [Holy Metropolis of Ioannina](http://www.imioanninon.gr/main/) for clothes, foods and medications for our fellow human beings.
**Available**: VAT(50) + VAT(20) + VAT(20) + VAT(50) + VAT(6) + VAT(20) + VAT(100) + VAT(20) + VAT(20) + VAT(50) + VAT(30) + VAT(50) + VAT(20) + VAT(5) - 13 = 47,45 + 18,97 + 18,61 + 47,05 + 5,34 + 18,97 + 98,04 + 18,97 + 18,61 + 47,95 + 28,24 + 47,05 + 18,97 + 4,59 - 13 - 424 = **Available**: VAT(50) + VAT(20) + VAT(20) + VAT(50) + VAT(6) + VAT(20) + VAT(100) + VAT(20) + VAT(20) + VAT(50) + VAT(30) + VAT(50) + VAT(20) + VAT(5) + VAT(25) - 13 = 47,45 + 18,97 + 18,61 + 47,05 + 5,34 + 18,97 + 98,04 + 18,97 + 18,61 + 47,95 + 28,24 + 47,05 + 18,97 + 4,59 + 23,80 - 13 - 424 =
424,92 EUR - 424 = **0,92** 424,92 - 424 = **24,72 EUR**

104
README.md
View File

@ -11,16 +11,14 @@
<a href="https://golang.org"><img src="https://img.shields.io/badge/powered_by-go-6362c2.svg?style=flat-square" alt="Built with GoLang"></a> <a href="https://golang.org"><img src="https://img.shields.io/badge/powered_by-go-6362c2.svg?style=flat-square" alt="Built with GoLang"></a>
<a href="https://golang.org"><img src="https://img.shields.io/badge/platform-any-ec2eb4.svg?style=flat-square" alt="Cross framework"></a> <a href="https://golang.org"><img src="https://img.shields.io/badge/platform-any-ec2eb4.svg?style=flat-square" alt="Cross framework"></a>
<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"><img src="https://img.shields.io/badge/open-%20source-thisismycolor.svg?logo=data:image%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAwIDEwMDAiPjxwYXRoIGZpbGw9InJnYigyMjAsMjIwLDIyMCkiIGQ9Ik04ODYuNiwzMDUuM2MtNDUuNywyMDMuMS0xODcsMzEwLjMtNDA5LjYsMzEwLjNoLTc0LjFsLTUxLjUsMzI2LjloLTYybC0zLjIsMjEuMWMtMi4xLDE0LDguNiwyNi40LDIyLjYsMjYuNGgxNTguNWMxOC44LDAsMzQuNy0xMy42LDM3LjctMzIuMmwxLjUtOGwyOS45LTE4OS4zbDEuOS0xMC4zYzIuOS0xOC42LDE4LjktMzIuMiwzNy43LTMyLjJoMjMuNWMxNTMuNSwwLDI3My43LTYyLjQsMzA4LjktMjQyLjdDOTIxLjYsNDA2LjgsOTE2LjcsMzQ4LjYsODg2LjYsMzA1LjN6Ii8%2BPHBhdGggZmlsbD0icmdiKDIyMCwyMjAsMjIwKSIgZD0iTTc5MS45LDgzLjlDNzQ2LjUsMzIuMiw2NjQuNCwxMCw1NTkuNSwxMEgyNTVjLTIxLjQsMC0zOS44LDE1LjUtNDMuMSwzNi44TDg1LDg1MWMtMi41LDE1LjksOS44LDMwLjIsMjUuOCwzMC4ySDI5OWw0Ny4zLTI5OS42bC0xLjUsOS40YzMuMi0yMS4zLDIxLjQtMzYuOCw0Mi45LTM2LjhINDc3YzE3NS41LDAsMzEzLTcxLjIsMzUzLjItMjc3LjVjMS4yLTYuMSwyLjMtMTIuMSwzLjEtMTcuOEM4NDUuMSwxODIuOCw4MzMuMiwxMzAuOCw3OTEuOSw4My45TDc5MS45LDgzLjl6Ii8%2BPC9zdmc%2B" alt="Donation"></a> <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=kataras2006%40hotmail%2ecom&lc=GR&item_name=Iris%20web%20framework&item_number=iriswebframeworkdonationid2016&currency_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted"><img src="https://img.shields.io/badge/open-%20source-thisismycolor.svg?logo=data:image%2Fsvg%2Bxml%3Bbase64%2CPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMDAwIDEwMDAiPjxwYXRoIGZpbGw9InJnYigyMjAsMjIwLDIyMCkiIGQ9Ik04ODYuNiwzMDUuM2MtNDUuNywyMDMuMS0xODcsMzEwLjMtNDA5LjYsMzEwLjNoLTc0LjFsLTUxLjUsMzI2LjloLTYybC0zLjIsMjEuMWMtMi4xLDE0LDguNiwyNi40LDIyLjYsMjYuNGgxNTguNWMxOC44LDAsMzQuNy0xMy42LDM3LjctMzIuMmwxLjUtOGwyOS45LTE4OS4zbDEuOS0xMC4zYzIuOS0xOC42LDE4LjktMzIuMiwzNy43LTMyLjJoMjMuNWMxNTMuNSwwLDI3My43LTYyLjQsMzA4LjktMjQyLjdDOTIxLjYsNDA2LjgsOTE2LjcsMzQ4LjYsODg2LjYsMzA1LjN6Ii8%2BPHBhdGggZmlsbD0icmdiKDIyMCwyMjAsMjIwKSIgZD0iTTc5MS45LDgzLjlDNzQ2LjUsMzIuMiw2NjQuNCwxMCw1NTkuNSwxMEgyNTVjLTIxLjQsMC0zOS44LDE1LjUtNDMuMSwzNi44TDg1LDg1MWMtMi41LDE1LjksOS44LDMwLjIsMjUuOCwzMC4ySDI5OWw0Ny4zLTI5OS42bC0xLjUsOS40YzMuMi0yMS4zLDIxLjQtMzYuOCw0Mi45LTM2LjhINDc3YzE3NS41LDAsMzEzLTcxLjIsMzUzLjItMjc3LjVjMS4yLTYuMSwyLjMtMTIuMSwzLjEtMTcuOEM4NDUuMSwxODIuOCw4MzMuMiwxMzAuOCw3OTEuOSw4My45TDc5MS45LDgzLjl6Ii8%2BPC9zdmc%2B" alt="Donation"></a>
<br/> <br/>
<a href="https://github.com/kataras/iris/blob/master/HISTORY.md"><img src="https://img.shields.io/badge/%20version%20-%206.0.5%20-blue.svg?style=flat-square" alt="CHANGELOG/HISTORY"></a> <a href="https://github.com/kataras/iris/blob/master/HISTORY.md"><img src="https://img.shields.io/badge/%20version%20-%206.0.6%20-blue.svg?style=flat-square" alt="CHANGELOG/HISTORY"></a>
<a href="https://github.com/iris-contrib/examples"><img src="https://img.shields.io/badge/%20examples-repository-3362c2.svg?style=flat-square" alt="Examples"></a> <a href="https://github.com/iris-contrib/examples"><img src="https://img.shields.io/badge/%20examples-repository-3362c2.svg?style=flat-square" alt="Examples"></a>
@ -647,6 +645,104 @@ DestroyAllSessions()
### Websockets ### Websockets
Server configuration
```go
iris.Config.Websocket{
// WriteTimeout time allowed to write a message to the connection.
// Default value is 15 * time.Second
WriteTimeout time.Duration
// PongTimeout allowed to read the next pong message from the connection
// Default value is 60 * time.Second
PongTimeout time.Duration
// PingPeriod send ping messages to the connection with this period. Must be less than PongTimeout
// Default value is (PongTimeout * 9) / 10
PingPeriod time.Duration
// MaxMessageSize max message size allowed from connection
// Default value is 1024
MaxMessageSize int64
// BinaryMessages set it to true in order to denotes binary data messages instead of utf-8 text
// see https://github.com/kataras/iris/issues/387#issuecomment-243006022 for more
// Defaults to false
BinaryMessages bool
// Endpoint is the path which the websocket server will listen for clients/connections
// Default value is empty string, if you don't set it the Websocket server is disabled.
Endpoint string
// ReadBufferSize is the buffer size for the underline reader
ReadBufferSize int
// WriteBufferSize is the buffer size for the underline writer
WriteBufferSize int
// Error specifies the function for generating HTTP error responses.
//
// The default behavior is to store the reason in the context (ctx.Set(reason)) and fire any custom error (ctx.EmitError(status))
Error func(ctx *Context, status int, reason error)
// CheckOrigin returns true if the request Origin header is acceptable. If
// CheckOrigin is nil, the host in the Origin header must not be set or
// must match the host of the request.
//
// The default behavior is to allow all origins
// you can change this behavior by setting the iris.Config.Websocket.CheckOrigin = iris.WebsocketCheckSameOrigin
CheckOrigin func(r *http.Request) bool
// IDGenerator used to create (and later on, set)
// an ID for each incoming websocket connections (clients).
// If empty then the ID is generated by the result of 64
// random combined characters
IDGenerator func(r *http.Request) string
}
```
Connection's methods
```go
ID() string
Request() *http.Request
// Receive from the client
On("anyCustomEvent", func(message string) {})
On("anyCustomEvent", func(message int){})
On("anyCustomEvent", func(message bool){})
On("anyCustomEvent", func(message anyCustomType){})
On("anyCustomEvent", func(){})
// Receive a native websocket message from the client
// compatible without need of import the iris-ws.js to the .html
OnMessage(func(message []byte){})
// Send to the client
Emit("anyCustomEvent", string)
Emit("anyCustomEvent", int)
Emit("anyCustomEvent", bool)
Emit("anyCustomEvent", anyCustomType)
// Send native websocket messages
// with config.BinaryMessages = true
// useful when you use proto or something like this.
EmitMessage([]byte("anyMessage"))
// Send to specific client(s)
To("otherConnectionId").Emit/EmitMessage...
To("anyCustomRoom").Emit/EmitMessage...
// Send to all opened connections/clients
To(websocket.All).Emit/EmitMessage...
// Send to all opened connections/clients EXCEPT this client
To(websocket.Broadcast).Emit/EmitMessage...
// Rooms, group of connections/clients
Join("anyCustomRoom")
Leave("anyCustomRoom")
// Fired when the connection is closed
OnDisconnect(func(){})
// Force-disconnect the client from the server-side
Disconnect() error
```
```go ```go
// file ./main.go // file ./main.go
package main package main
@ -847,7 +943,7 @@ I recommend writing your API tests using this new library, [httpexpect](https://
Versioning Versioning
------------ ------------
Current: **v6.0.5** Current: **v6.0.6**
Stable: **[v5/fasthttp](https://github.com/kataras/iris/tree/5.0.0)** Stable: **[v5/fasthttp](https://github.com/kataras/iris/tree/5.0.0)**

View File

@ -606,10 +606,6 @@ type WebsocketConfiguration struct {
ReadBufferSize int ReadBufferSize int
// WriteBufferSize is the buffer size for the underline writer // WriteBufferSize is the buffer size for the underline writer
WriteBufferSize int WriteBufferSize int
// Headers if true then the client's headers are copy to the websocket connection
//
// Default is true
Headers bool
// Error specifies the function for generating HTTP error responses. // Error specifies the function for generating HTTP error responses.
// //
// The default behavior is to store the reason in the context (ctx.Set(reason)) and fire any custom error (ctx.EmitError(status)) // The default behavior is to store the reason in the context (ctx.Set(reason)) and fire any custom error (ctx.EmitError(status))
@ -621,6 +617,11 @@ type WebsocketConfiguration struct {
// The default behavior is to allow all origins // The default behavior is to allow all origins
// you can change this behavior by setting the iris.Config.Websocket.CheckOrigin = iris.WebsocketCheckSameOrigin // you can change this behavior by setting the iris.Config.Websocket.CheckOrigin = iris.WebsocketCheckSameOrigin
CheckOrigin func(r *http.Request) bool CheckOrigin func(r *http.Request) bool
// IDGenerator used to create (and later on, set)
// an ID for each incoming websocket connections (clients).
// If empty then the ID is generated by the result of 64
// random combined characters
IDGenerator func(r *http.Request) string
} }
var ( var (
@ -679,12 +680,7 @@ var (
c.Websocket.WriteBufferSize = val c.Websocket.WriteBufferSize = val
} }
} }
// OptionWebsocketHeaders if true then the client's headers are copy to the websocket connection
OptionWebsocketHeaders = func(val bool) OptionSet {
return func(c *Configuration) {
c.Websocket.Headers = val
}
}
// OptionWebsocketError specifies the function for generating HTTP error responses. // OptionWebsocketError specifies the function for generating HTTP error responses.
OptionWebsocketError = func(val func(*Context, int, error)) OptionSet { OptionWebsocketError = func(val func(*Context, int, error)) OptionSet {
return func(c *Configuration) { return func(c *Configuration) {
@ -699,6 +695,16 @@ var (
c.Websocket.CheckOrigin = val c.Websocket.CheckOrigin = val
} }
} }
// OptionWebsocketIDGenerator used to create (and later on, set)
// an ID for each incoming websocket connections (clients).
// If empty then the ID is generated by the result of 64
// random combined characters
OptionWebsocketIDGenerator = func(val func(*http.Request) string) OptionSet {
return func(c *Configuration) {
c.Websocket.IDGenerator = val
}
}
) )
const ( const (
@ -748,7 +754,8 @@ func DefaultWebsocketConfiguration() WebsocketConfiguration {
ReadBufferSize: 4096, ReadBufferSize: 4096,
WriteBufferSize: 4096, WriteBufferSize: 4096,
Endpoint: "", Endpoint: "",
Headers: true, // use the kataras/go-websocket default
IDGenerator: nil,
} }
} }

16
iris.go
View File

@ -9,8 +9,8 @@ package main
import "github.com/kataras/iris" import "github.com/kataras/iris"
func main() { func main() {
iris.Get("/hi_json", func(c *iris.Context) { iris.Get("/hi_json", func(ctx *iris.Context) {
c.JSON(iris.StatusOK, iris.Map{ ctx.JSON(iris.StatusOK, iris.Map{
"Name": "Iris", "Name": "Iris",
"Released": "13 March 2016", "Released": "13 March 2016",
"Stars": "5883", "Stars": "5883",
@ -27,8 +27,8 @@ import "github.com/kataras/iris"
func main() { func main() {
s1 := iris.New() s1 := iris.New()
s1.Get("/hi_json", func(c *iris.Context) { s1.Get("/hi_json", func(ctx *iris.Context) {
c.JSON(iris.StatusOK, iris.Map{ ctx.JSON(iris.StatusOK, iris.Map{
"Name": "Iris", "Name": "Iris",
"Released": "13 March 2016", "Released": "13 March 2016",
"Stars": "5883", "Stars": "5883",
@ -36,8 +36,8 @@ func main() {
}) })
s2 := iris.New() s2 := iris.New()
s2.Get("/hi_raw_html", func(c *iris.Context) { s2.Get("/hi_raw_html", func(ctx *iris.Context) {
c.HTML(iris.StatusOK, "<b> Iris </b> welcomes <h1>you!</h1>") ctx.HTML(iris.StatusOK, "<b> Iris </b> welcomes <h1>you!</h1>")
}) })
go s1.Listen(":8080") go s1.Listen(":8080")
@ -47,7 +47,7 @@ func main() {
---------------------------------------------------------------------- ----------------------------------------------------------------------
For middleware, template engines, response engines, sessions, websockets, mails, subdomains, For middleware, template engines, response engines, sessions, websockets, mails, subdomains,
dynamic subdomains, routes, party of subdomains & routes, ssh and much more dynamic subdomains, routes, party of subdomains & routes and more
visit https://docs.iris-go.com visit https://docs.iris-go.com
*/ */
@ -81,7 +81,7 @@ const (
// IsLongTermSupport flag is true when the below version number is a long-term-support version // IsLongTermSupport flag is true when the below version number is a long-term-support version
IsLongTermSupport = false IsLongTermSupport = false
// Version is the current version number of the Iris web framework // Version is the current version number of the Iris web framework
Version = "6.0.5" Version = "6.0.6"
banner = ` _____ _ banner = ` _____ _
|_ _| (_) |_ _| (_)

View File

@ -83,6 +83,7 @@ func (ws *WebsocketServer) init() {
ws.station.ReleaseCtx(ctx) ws.station.ReleaseCtx(ctx)
}, },
CheckOrigin: c.CheckOrigin, CheckOrigin: c.CheckOrigin,
IDGenerator: c.IDGenerator,
}) })
} }