websocket.go 890 B

12345678910111213141516171819202122232425262728293031323334
  1. package websocket
  2. import (
  3. "crypto/sha1"
  4. "encoding/base64"
  5. "net/http"
  6. "github.com/gorilla/websocket"
  7. )
  8. // IsWebSocketUpgrade checks to see if the request is a WebSocket connection.
  9. func IsWebSocketUpgrade(req *http.Request) bool {
  10. return websocket.IsWebSocketUpgrade(req)
  11. }
  12. // NewResponseHeader returns headers needed to return to origin for completing handshake
  13. func NewResponseHeader(req *http.Request) http.Header {
  14. header := http.Header{}
  15. header.Add("Connection", "Upgrade")
  16. header.Add("Sec-Websocket-Accept", generateAcceptKey(req.Header.Get("Sec-WebSocket-Key")))
  17. header.Add("Upgrade", "websocket")
  18. return header
  19. }
  20. // from RFC-6455
  21. var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
  22. func generateAcceptKey(challengeKey string) string {
  23. h := sha1.New()
  24. h.Write([]byte(challengeKey))
  25. h.Write(keyGUID)
  26. return base64.StdEncoding.EncodeToString(h.Sum(nil))
  27. }