@@ -27,6 +27,7 @@ import (
27
27
"testing"
28
28
"time"
29
29
30
+ "golang.org/x/net/http2"
30
31
"google.golang.org/grpc"
31
32
"google.golang.org/grpc/connectivity"
32
33
"google.golang.org/grpc/credentials/insecure"
@@ -110,8 +111,7 @@ func RegisterServiceServerOption(f func(*grpc.Server)) grpc.ServerOption {
110
111
return & registerServiceServerOption {f : f }
111
112
}
112
113
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 ) {
115
115
if ss .Network == "" {
116
116
ss .Network = "tcp"
117
117
}
@@ -127,24 +127,59 @@ func (ss *StubServer) StartServer(sopts ...grpc.ServerOption) error {
127
127
var err error
128
128
lis , err = net .Listen (ss .Network , ss .Address )
129
129
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 )
131
131
}
132
132
}
133
133
ss .Address = lis .Addr ().String ()
134
- ss .cleanups = append (ss .cleanups , func () { lis .Close () })
135
134
136
- s : = grpc .NewServer (sopts ... )
135
+ ss . S = grpc .NewServer (sopts ... )
137
136
for _ , so := range sopts {
138
137
switch x := so .(type ) {
139
138
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 )
141
166
}
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
142
179
}
143
180
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
+
148
183
return nil
149
184
}
150
185
0 commit comments