File: upgrade.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (32 lines) | stat: -rw-r--r-- 908 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package response

import (
	"errors"
	"fmt"
	"net"
	"strings"
	"time"
)

// Upgrade takes a hijacked HTTP connection and sends the HTTP 101 Switching Protocols headers for protocolName.
func Upgrade(hijackedConn net.Conn, protocolName string) error {
	// Write the status line and upgrade header by hand since w.WriteHeader() would fail after Hijack().
	sb := strings.Builder{}
	sb.WriteString("HTTP/1.1 101 Switching Protocols\r\n")
	sb.WriteString(fmt.Sprintf("Upgrade: %s\r\n", protocolName))
	sb.WriteString("Connection: Upgrade\r\n\r\n")

	_ = hijackedConn.SetWriteDeadline(time.Now().Add(time.Second * 5))
	n, err := hijackedConn.Write([]byte(sb.String()))
	_ = hijackedConn.SetWriteDeadline(time.Time{}) // Cancel deadline.

	if err != nil {
		return fmt.Errorf("Failed writing upgrade headers: %w", err)
	}

	if n != sb.Len() {
		return errors.New("Failed writing upgrade headers")
	}

	return nil
}