olahol / melody

:notes: Minimalist websocket framework for Go
BSD 2-Clause "Simplified" License
3.76k stars 365 forks source link

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

Closed CodeDing closed 1 year ago

CodeDing commented 1 year ago

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)
}

   ...

} `

CodeDing commented 1 year ago

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"}
CodeDing commented 1 year ago

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