koding / websocketproxy

WebSocket reverse proxy handler for Go
http://godoc.org/github.com/koding/websocketproxy
MIT License
429 stars 120 forks source link

feat: support cross-domain request, simplify code #10

Closed ansiz closed 7 years ago

ansiz commented 7 years ago
  1. it doesn't work when I try to proxy a server which cross-domain request is unsupported.
  2. it seems some code is unnecessary?
rjeczalik commented 7 years ago

Hey @ansiz, I believe what would work without changing API is to provide your custom Backend function that would add/modify the Origin header. The Backend function naming could be misleading, think of it as Director function.

Moreover we could not simply change the API due to backward-compatibility reasons - if I have a custom Director function that does more than the default one, it would be impossible for me to migrate it over once you removed the function.

ansiz commented 7 years ago

@rjeczalik Thanks for your quickly reply, yes you are right. I will try to implement according to your suggestion.

ansiz commented 7 years ago

@rjeczalik In addition, I try to use websocketproxy in my project which has a requirement to establish dozens of proxy handlers, I found those code here: https://github.com/koding/websocketproxy/blob/master/websocketproxy.go#L57-L61 can't be assign new value due to those code are in the anonymous function(closure), I'm not quite understand why we must copy those values if the handler can't be different in twice initialization, and why we copy those values? I mean the NewProxy is not really new even the incoming target url.URL is different, I'm not sure wether I made some mistakes or misunderstood? I feel sorry my English is not very good,hope you can understand and looking forward to your reply, thanks again : )

rjeczalik commented 7 years ago

@ansiz: and why we copy those values?

Since the r comes from the http.Handler and according to its documentation:

Except for reading the body, handlers should not modify the provided Request.

@ansiz: can't be assign new value due to those code are in the anonymous function(closure)

Just create a custom backend:

wp := &websocketproxy.WebsocketProxy{
    Backend: func(r *http.Request) *url.URL {
        u := *target
        u.Fragment = r.URL.Fragment
        u.Path = r.URL.Path
        u.RawQuery = r.URL.RawQuery

        return &u
    },
}

While writing this example I realised you would need to extend WebsocketProxy with some Header func(*http.Request) http.Header field that you can use to provide custom header. This would involve refactoring out L89-L119 to some separate function, say DefaultHeader.

ansiz commented 7 years ago

@rjeczalik Thanks a lot, you are really a nice and patient maintainer.

rjeczalik commented 7 years ago

Doing my best 😎 Thanks!