t.marcusの外部記憶装置

忘備録とかちょっとした考えとかをつらつらと...

HTTP/gRPCハイブリッドなアプリ

gRPCはHTTP/1.1で受けれないのでHTTP/2としてリクエストをハンドリングできるようにしてやって、HTTP/2かつapplication/grpcの場合にgrpc側で処理してやるようにすればOK

	addr := ":8080"
	if v, ok := os.LookupEnv("BIND"); ok {
		addr = v
	}

	grpcServer = grpc.NewServer()
	reflection.Register(grpcServer)

	mux := http.NewServeMux()
	mux.Handle("/live", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte{'o', 'k'})
	}))

	httpServer = &http.Server{
		Addr: addr,
		Handler: h2c.NewHandler(
			http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") {
					grpcServer.ServeHTTP(w, r)
				} else {
					mux.ServeHTTP(w, r)
				}
			}),
			&http2.Server{}),
	}

	httpServer.ListenAndServe()