olahol/melody

Example for adding option to setup websocket upgrader when creating melody instantce

CodeDing opened this issue · 2 comments

Hi,
When I want to use the great package melody to refactor the code that using gorilla/websocket directly in the project, I have encountered a problem that I can setup any field of the websocket.Upgrader if it is needed, but in melody library, when creating a melody instance using melody.New(), the websocket.Upgrader is created by default options and there is no exported method to alternate or add other option.

Now, I come up with a idea to bring the functionality to it without changing the code style of the melody.
The code looks like below. You can also reference the code in the pull request.

Thank you for your time to review it.

options.go
`
type Option func(*websocket.Upgrader)

func WithReadBufferSize(size int) Option {
return func(u *websocket.Upgrader) {
u.ReadBufferSize = size
}
}

func WithWriteBufferSize(size int) Option {
return func(u *websocket.Upgrader) {
u.WriteBufferSize = size
}
}

func WithHandshakeTimeout(d time.Duration) Option {
return func(u *websocket.Upgrader) {
u.HandshakeTimeout = d
}
}

func WithEnableCompression() Option {
return func(u *websocket.Upgrader) {
u.EnableCompression = true
}
}

func WithSubprotocols(protocols []string) Option {
return func(u *websocket.Upgrader) {
u.Subprotocols = protocols
}
}
`

melody.go
`
func New(opts ...Option) *Melody {
upgrader := &websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}

for _, opt := range opts {
	opt(upgrader)
}

   ...

}
`

Oh, ignore it, I have found a way to setup the field of the websocket.Upgrader, it looks like the code below

m.Upgrader.CheckOrigin = func(r *http.Request) bool { return true }
m.Upgrader.Subprotocols = []string{"Authorization"}

Due to the field of the websocket.Upgrader is capitalized,it can set the option directly.