grpc_routes.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package grpc // import "github.com/docker/docker/api/server/router/grpc"
  2. import (
  3. "context"
  4. "net/http"
  5. "github.com/pkg/errors"
  6. "golang.org/x/net/http2"
  7. )
  8. func (gr *grpcRouter) serveGRPC(ctx context.Context, w http.ResponseWriter, r *http.Request, vars map[string]string) error {
  9. h, ok := w.(http.Hijacker)
  10. if !ok {
  11. return errors.New("handler does not support hijack")
  12. }
  13. proto := r.Header.Get("Upgrade")
  14. if proto == "" {
  15. return errors.New("no upgrade proto in request")
  16. }
  17. if proto != "h2c" {
  18. return errors.Errorf("protocol %s not supported", proto)
  19. }
  20. conn, _, err := h.Hijack()
  21. if err != nil {
  22. return err
  23. }
  24. resp := &http.Response{
  25. StatusCode: http.StatusSwitchingProtocols,
  26. ProtoMajor: 1,
  27. ProtoMinor: 1,
  28. Header: http.Header{},
  29. }
  30. resp.Header.Set("Connection", "Upgrade")
  31. resp.Header.Set("Upgrade", proto)
  32. // set raw mode
  33. conn.Write([]byte{})
  34. resp.Write(conn)
  35. // https://godoc.org/golang.org/x/net/http2#Server.ServeConn
  36. // TODO: is it a problem that conn has already been written to?
  37. gr.h2Server.ServeConn(conn, &http2.ServeConnOpts{Handler: gr.grpcServer})
  38. return nil
  39. }