@@ -27,6 +27,7 @@ import (
2727 "testing"
2828 "time"
2929
30+ "golang.org/x/net/http2"
3031 "google.golang.org/grpc"
3132 "google.golang.org/grpc/connectivity"
3233 "google.golang.org/grpc/credentials/insecure"
@@ -110,8 +111,7 @@ func RegisterServiceServerOption(f func(*grpc.Server)) grpc.ServerOption {
110111 return & registerServiceServerOption {f : f }
111112}
112113
113- // StartServer only starts the server. It does not create a client to it.
114- func (ss * StubServer ) StartServer (sopts ... grpc.ServerOption ) error {
114+ func (ss * StubServer ) setupServer (sopts ... grpc.ServerOption ) (net.Listener , error ) {
115115 if ss .Network == "" {
116116 ss .Network = "tcp"
117117 }
@@ -127,24 +127,59 @@ func (ss *StubServer) StartServer(sopts ...grpc.ServerOption) error {
127127 var err error
128128 lis , err = net .Listen (ss .Network , ss .Address )
129129 if err != nil {
130- return fmt .Errorf ("net.Listen(%q, %q) = %v" , ss .Network , ss .Address , err )
130+ return nil , fmt .Errorf ("net.Listen(%q, %q) = %v" , ss .Network , ss .Address , err )
131131 }
132132 }
133133 ss .Address = lis .Addr ().String ()
134- ss .cleanups = append (ss .cleanups , func () { lis .Close () })
135134
136- s : = grpc .NewServer (sopts ... )
135+ ss . S = grpc .NewServer (sopts ... )
137136 for _ , so := range sopts {
138137 switch x := so .(type ) {
139138 case * registerServiceServerOption :
140- x .f (s )
139+ x .f (ss .S )
140+ }
141+ }
142+
143+ testgrpc .RegisterTestServiceServer (ss .S , ss )
144+ ss .cleanups = append (ss .cleanups , ss .S .Stop )
145+ return lis , nil
146+ }
147+
148+ // StartHandlerServer only starts an HTTP server with a gRPC server as the
149+ // handler. It does not create a client to it. Cannot be used in a StubServer
150+ // that also used StartServer.
151+ func (ss * StubServer ) StartHandlerServer (sopts ... grpc.ServerOption ) error {
152+ lis , err := ss .setupServer (sopts ... )
153+ if err != nil {
154+ return err
155+ }
156+
157+ go func () {
158+ hs := & http2.Server {}
159+ opts := & http2.ServeConnOpts {Handler : ss .S }
160+ for {
161+ conn , err := lis .Accept ()
162+ if err != nil {
163+ return
164+ }
165+ hs .ServeConn (conn , opts )
141166 }
167+ }()
168+ ss .cleanups = append (ss .cleanups , func () { lis .Close () })
169+
170+ return nil
171+ }
172+
173+ // StartServer only starts the server. It does not create a client to it.
174+ // Cannot be used in a StubServer that also used StartHandlerServer.
175+ func (ss * StubServer ) StartServer (sopts ... grpc.ServerOption ) error {
176+ lis , err := ss .setupServer (sopts ... )
177+ if err != nil {
178+ return err
142179 }
143180
144- testgrpc .RegisterTestServiceServer (s , ss )
145- go s .Serve (lis )
146- ss .cleanups = append (ss .cleanups , s .Stop )
147- ss .S = s
181+ go ss .S .Serve (lis )
182+
148183 return nil
149184}
150185
0 commit comments