server.go 1.49 KB
Newer Older
1 2 3 4 5 6
package main

import (
	"crypto/tls"
	"golang.org/x/net/http2"
	"net/http"
7 8 9 10
"net"
	"time"
	"os"
	"fmt"
11 12
)

13
type tlsHandlerFunc func(*tls.ClientHelloInfo) (*tls.Certificate, error)
14

15 16 17
type tcpKeepAliveListener struct {
	*net.TCPListener
}
18

19 20 21 22
func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
	tc, err := ln.AcceptTCP()
	if err != nil {
		return
23
	}
24 25 26
	tc.SetKeepAlive(true)
	tc.SetKeepAlivePeriod(3 * time.Minute)
	return tc, nil
27 28
}

29
func listenAndServe(fd uintptr, handler http.HandlerFunc, tlsConfig *tls.Config) error {
30
	// create server
31
	server := &http.Server{Handler: handler, TLSConfig: tlsConfig}
32 33 34 35 36 37 38 39

	if *http2proto {
		err := http2.ConfigureServer(server, &http2.Server{})
		if err != nil {
			return err
		}
	}

40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
	l, err := net.FileListener(os.NewFile(fd, "[socket]"))
	if err != nil {
		return fmt.Errorf("failed to listen on FD %d: %v", fd, err)
	}

	if tlsConfig != nil {
		tlsListener := tls.NewListener(tcpKeepAliveListener{l.(*net.TCPListener)}, server.TLSConfig)
		return server.Serve(tlsListener)
	} else {
		return server.Serve(&tcpKeepAliveListener{l.(*net.TCPListener)})
	}
}

func listenAndServeTLS(fd uintptr, cert, key []byte, handler http.HandlerFunc, tlsHandler tlsHandlerFunc) error {
	certificate, err := tls.X509KeyPair(cert, key)
	if err != nil {
		return err
	}

	tlsConfig := &tls.Config{}
	tlsConfig.GetCertificate = tlsHandler
	tlsConfig.NextProtos = []string {
		"http/1.1",
	}
	tlsConfig.Certificates = []tls.Certificate{
		certificate,
	}
	return listenAndServe(fd, handler, tlsConfig)
68
}