package websocket

import (
	"fmt"
	"net"
	"net/http"
)

func Upgrade(w http.ResponseWriter, wsKey string) (net.Conn, error) {
	h, ok := w.(http.Hijacker)
	if !ok {
		return nil, fmt.Errorf("cannot hijack")
	}

	conn, buf, err := h.Hijack()
	if err != nil {
		return nil, err
	}

	// WebSocket handshake response
	fmt.Fprintf(buf,
		"HTTP/1.1 101 Switching Protocols\r\n"+
			"Upgrade: websocket\r\n"+
			"Connection: Upgrade\r\n"+
			"Sec-WebSocket-Accept: %s\r\n\r\n", computeAcceptKey(wsKey))
	buf.Flush()

	return conn, nil
}
