-
Notifications
You must be signed in to change notification settings - Fork 325
/
generator.go
1667 lines (1530 loc) · 65.1 KB
/
generator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 Twitch Interactive, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may not
// use this file except in compliance with the License. A copy of the License is
// located at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// or in the "license" file accompanying this file. This file is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"bufio"
"bytes"
"compress/gzip"
"fmt"
"go/parser"
"go/printer"
"go/token"
"path"
"sort"
"strconv"
"strings"
"google.golang.org/protobuf/proto"
descriptor "google.golang.org/protobuf/types/descriptorpb"
plugin "google.golang.org/protobuf/types/pluginpb"
"github.com/pkg/errors"
"github.com/twitchtv/twirp/internal/gen"
"github.com/twitchtv/twirp/internal/gen/stringutils"
"github.com/twitchtv/twirp/internal/gen/typemap"
)
type twirp struct {
filesHandled int
reg *typemap.Registry
// Map to record whether we've built each package
pkgs map[string]string
pkgNamesInUse map[string]bool
importPrefix string // String to prefix to imported package file names.
importMap map[string]string // Mapping from .proto file name to import path.
// Package output:
sourceRelativePaths bool // instruction on where to write output files
modulePrefix string
// Package naming:
genPkgName string // Name of the package that we're generating
fileToGoPackageName map[*descriptor.FileDescriptorProto]string
// List of files that were inputs to the generator. We need to hold this in
// the struct so we can write a header for the file that lists its inputs.
genFiles []*descriptor.FileDescriptorProto
// Output buffer that holds the bytes we want to write out for a single file.
// Gets reset after working on a file.
output *bytes.Buffer
}
func newGenerator() *twirp {
t := &twirp{
pkgs: make(map[string]string),
pkgNamesInUse: make(map[string]bool),
importMap: make(map[string]string),
fileToGoPackageName: make(map[*descriptor.FileDescriptorProto]string),
output: bytes.NewBuffer(nil),
}
return t
}
func (t *twirp) Generate(in *plugin.CodeGeneratorRequest) *plugin.CodeGeneratorResponse {
params, err := parseCommandLineParams(in.GetParameter())
if err != nil {
gen.Fail("could not parse parameters passed to --twirp_out", err.Error())
}
t.importPrefix = params.importPrefix
t.importMap = params.importMap
t.sourceRelativePaths = params.paths == "source_relative"
t.modulePrefix = params.module
t.genFiles = gen.FilesToGenerate(in)
// Collect information on types.
t.reg = typemap.New(in.ProtoFile)
// Register names of packages that we import.
t.registerPackageName("bytes")
t.registerPackageName("strings")
t.registerPackageName("path")
t.registerPackageName("ctxsetters")
t.registerPackageName("context")
t.registerPackageName("http")
t.registerPackageName("io")
t.registerPackageName("json")
t.registerPackageName("protojson")
t.registerPackageName("proto")
t.registerPackageName("strconv")
t.registerPackageName("twirp")
t.registerPackageName("url")
t.registerPackageName("fmt")
t.registerPackageName("errors")
// Time to figure out package names of objects defined in protobuf. First,
// we'll figure out the name for the package we're generating.
genPkgName, err := deduceGenPkgName(t.genFiles)
if err != nil {
gen.Fail(err.Error())
}
t.genPkgName = genPkgName
// We also need to figure out the fully import path of the package we're
// generating. It's possible to import proto definitions from different .proto
// files which will be generated into the same Go package, which we need to
// detect (and can only detect if files use fully-specified go_package
// options).
genPkgImportPath, _, _ := goPackageOption(t.genFiles[0])
// Next, we need to pick names for all the files that are dependencies.
for _, f := range in.ProtoFile {
// Is this is a file we are generating? If yes, it gets the shared package name.
if fileDescSliceContains(t.genFiles, f) {
t.fileToGoPackageName[f] = t.genPkgName
continue
}
// Is this is an imported .proto file which has the same fully-specified
// go_package as the targeted file for generation? If yes, it gets the
// shared package name too.
if genPkgImportPath != "" {
importPath, _, _ := goPackageOption(f)
if importPath == genPkgImportPath {
t.fileToGoPackageName[f] = t.genPkgName
continue
}
}
// This is a dependency from a different go_package. Use its package name.
name := f.GetPackage()
if name == "" {
name = stringutils.BaseName(f.GetName())
}
name = stringutils.CleanIdentifier(name)
alias := t.registerPackageName(name)
t.fileToGoPackageName[f] = alias
}
// Showtime! Generate the response.
resp := new(plugin.CodeGeneratorResponse)
resp.SupportedFeatures = proto.Uint64(uint64(plugin.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL))
for _, f := range t.genFiles {
respFile := t.generate(f)
if respFile != nil {
resp.File = append(resp.File, respFile)
}
}
return resp
}
func (t *twirp) registerPackageName(name string) (alias string) {
alias = name
i := 1
for t.pkgNamesInUse[alias] {
alias = name + strconv.Itoa(i)
i++
}
t.pkgNamesInUse[alias] = true
t.pkgs[name] = alias
return alias
}
// deduceGenPkgName figures out the go package name to use for generated code.
// Will try to use the explicit go_package setting in a file (if set, must be
// consistent in all files). If no files have go_package set, then use the
// protobuf package name (must be consistent in all files)
func deduceGenPkgName(genFiles []*descriptor.FileDescriptorProto) (string, error) {
var genPkgName string
for _, f := range genFiles {
name, explicit := goPackageName(f)
if explicit {
name = stringutils.CleanIdentifier(name)
if genPkgName != "" && genPkgName != name {
// Make sure they're all set consistently.
return "", errors.Errorf("files have conflicting go_package settings, must be the same: %q and %q", genPkgName, name)
}
genPkgName = name
}
}
if genPkgName != "" {
return genPkgName, nil
}
// If there is no explicit setting, then check the implicit package name
// (derived from the protobuf package name) of the files and make sure it's
// consistent.
for _, f := range genFiles {
name, _ := goPackageName(f)
name = stringutils.CleanIdentifier(name)
if genPkgName != "" && genPkgName != name {
return "", errors.Errorf("files have conflicting package names, must be the same or overridden with go_package: %q and %q", genPkgName, name)
}
genPkgName = name
}
// All the files have the same name, so we're good.
return genPkgName, nil
}
func (t *twirp) generate(file *descriptor.FileDescriptorProto) *plugin.CodeGeneratorResponse_File {
resp := new(plugin.CodeGeneratorResponse_File)
if len(file.Service) == 0 {
return nil
}
t.generateFileHeader(file)
t.generateImports(file)
if t.filesHandled == 0 {
t.generateUtilImports()
}
t.generateVersionCheck(file)
// For each service, generate client stubs and server
for i, service := range file.Service {
t.generateService(file, service, i)
}
// Util functions only generated once per package
if t.filesHandled == 0 {
t.generateUtils()
}
t.generateFileDescriptor(file)
resp.Name = proto.String(t.goFileName(file))
resp.Content = proto.String(t.formattedOutput())
t.output.Reset()
t.filesHandled++
return resp
}
func (t *twirp) generateVersionCheck(file *descriptor.FileDescriptorProto) {
t.P(`// Version compatibility assertion.`)
t.P(`// If the constant is not defined in the package, that likely means`)
t.P(`// the package needs to be updated to work with this generated code.`)
t.P(`// See https://twitchtv.github.io/twirp/docs/version_matrix.html`)
t.P(`const _ = `, t.pkgs["twirp"], `.TwirpPackageMinVersion_8_1_0`)
}
func (t *twirp) generateFileHeader(file *descriptor.FileDescriptorProto) {
t.P("// Code generated by protoc-gen-twirp ", gen.Version, ", DO NOT EDIT.")
t.P("// source: ", file.GetName())
t.P()
comment, err := t.reg.FileComments(file)
if err == nil && comment.Leading != "" {
for _, line := range strings.Split(comment.Leading, "\n") {
if line != "" {
t.P("// " + strings.TrimPrefix(line, " "))
}
}
t.P()
}
t.P(`package `, t.genPkgName)
t.P()
}
func (t *twirp) generateImports(file *descriptor.FileDescriptorProto) {
if len(file.Service) == 0 {
return
}
// stdlib imports
t.P(`import `, t.pkgs["context"], ` "context"`)
t.P(`import `, t.pkgs["fmt"], ` "fmt"`)
t.P(`import `, t.pkgs["http"], ` "net/http"`)
t.P(`import `, t.pkgs["io"], ` "io"`)
t.P(`import `, t.pkgs["json"], ` "encoding/json"`)
t.P(`import `, t.pkgs["strconv"], ` "strconv"`)
t.P(`import `, t.pkgs["strings"], ` "strings"`)
t.P()
// dependency imports
t.P(`import `, t.pkgs["protojson"], ` "google.golang.org/protobuf/encoding/protojson"`)
t.P(`import `, t.pkgs["proto"], ` "google.golang.org/protobuf/proto"`)
t.P(`import `, t.pkgs["twirp"], ` "github.com/twitchtv/twirp"`)
t.P(`import `, t.pkgs["ctxsetters"], ` "github.com/twitchtv/twirp/ctxsetters"`)
t.P()
// It's legal to import a message and use it as an input or output for a
// method. Make sure to import the package of any such message. First, dedupe
// them.
deps := make(map[string]string) // Map of package name to quoted import path.
ourImportPath := path.Dir(t.goFileName(file))
for _, s := range file.Service {
for _, m := range s.Method {
defs := []*typemap.MessageDefinition{
t.reg.MethodInputDefinition(m),
t.reg.MethodOutputDefinition(m),
}
for _, def := range defs {
importPath, _ := parseGoPackageOption(def.File.GetOptions().GetGoPackage())
if importPath == "" { // no option go_package
importPath := path.Dir(t.goFileName(def.File)) // use the dirname of the Go filename as import path
if importPath == ourImportPath {
continue
}
}
if substitution, ok := t.importMap[def.File.GetName()]; ok {
importPath = substitution
}
importPath = t.importPrefix + importPath
pkg := t.goPackageName(def.File)
if pkg != t.genPkgName {
deps[pkg] = strconv.Quote(importPath)
}
}
}
}
pkgs := make([]string, 0, len(deps))
for pkg := range deps {
pkgs = append(pkgs, pkg)
}
sort.Strings(pkgs)
for _, pkg := range pkgs {
t.P(`import `, pkg, ` `, deps[pkg])
}
if len(deps) > 0 {
t.P()
}
}
// generateUtilImports are imports that are only used on utility functions.
// If there are multiple proto files being generated, they are only included in the first one of them.
func (t *twirp) generateUtilImports() {
t.P(`import `, t.pkgs["bytes"], ` "bytes"`)
t.P(`import `, t.pkgs["errors"], ` "errors"`)
t.P(`import `, t.pkgs["path"], ` "path"`)
t.P(`import `, t.pkgs["url"], ` "net/url"`)
}
// Generate utility functions used in Twirp code.
// These functions are generated only once per package; when generating for
// multiple services they are declared only once.
func (t *twirp) generateUtils() {
t.sectionComment(`Utils`)
t.P(`// HTTPClient is the interface used by generated clients to send HTTP requests.`)
t.P(`// It is fulfilled by *(net/http).Client, which is sufficient for most users.`)
t.P(`// Users can provide their own implementation for special retry policies.`)
t.P(`// `)
t.P(`// HTTPClient implementations should not follow redirects. Redirects are`)
t.P(`// automatically disabled if *(net/http).Client is passed to client`)
t.P(`// constructors. See the withoutRedirects function in this file for more`)
t.P(`// details.`)
t.P(`type HTTPClient interface {`)
t.P(` Do(req *`, t.pkgs["http"], `.Request) (*`, t.pkgs["http"], `.Response, error)`)
t.P(`}`)
t.P()
t.P(`// TwirpServer is the interface generated server structs will support: they're`)
t.P(`// HTTP handlers with additional methods for accessing metadata about the`)
t.P(`// service. Those accessors are a low-level API for building reflection tools.`)
t.P(`// Most people can think of TwirpServers as just http.Handlers.`)
t.P(`type TwirpServer interface {`)
t.P(` `, t.pkgs["http"], `.Handler`)
t.P()
t.P(` // ServiceDescriptor returns gzipped bytes describing the .proto file that`)
t.P(` // this service was generated from. Once unzipped, the bytes can be`)
t.P(` // unmarshalled as a`)
t.P(` // google.golang.org/protobuf/types/descriptorpb.FileDescriptorProto.`)
t.P(` //`)
t.P(` // The returned integer is the index of this particular service within that`)
t.P(` // FileDescriptorProto's 'Service' slice of ServiceDescriptorProtos. This is a`)
t.P(` // low-level field, expected to be used for reflection.`)
t.P(` ServiceDescriptor() ([]byte, int)`)
t.P()
t.P(` // ProtocGenTwirpVersion is the semantic version string of the version of`)
t.P(` // twirp used to generate this file.`)
t.P(` ProtocGenTwirpVersion() string`)
t.P()
t.P(` // PathPrefix returns the HTTP URL path prefix for all methods handled by this`)
t.P(` // service. This can be used with an HTTP mux to route Twirp requests.`)
t.P(` // The path prefix is in the form: "/<prefix>/<package>.<Service>/"`)
t.P(` // that is, everything in a Twirp route except for the <Method> at the end.`)
t.P(` PathPrefix() string`)
t.P(`}`)
t.P()
t.P(`func newServerOpts(opts []interface{}) *`, t.pkgs["twirp"], `.ServerOptions {`)
t.P(` serverOpts := &`, t.pkgs["twirp"], `.ServerOptions{}`)
t.P(` for _, opt := range opts {`)
t.P(` switch o := opt.(type) {`)
t.P(` case `, t.pkgs["twirp"], `.ServerOption:`)
t.P(` o(serverOpts)`)
t.P(` case *`, t.pkgs["twirp"], `.ServerHooks: // backwards compatibility, allow to specify hooks as an argument`)
t.P(` twirp.WithServerHooks(o)(serverOpts)`)
t.P(` case nil: // backwards compatibility, allow nil value for the argument`)
t.P(` continue`)
t.P(` default:`)
t.P(` panic(`, t.pkgs["fmt"], `.Sprintf("Invalid option type %T, please use a twirp.ServerOption", o))`)
t.P(` }`)
t.P(` }`)
t.P(` return serverOpts`)
t.P(`}`)
t.P()
t.P(`// WriteError writes an HTTP response with a valid Twirp error format (code, msg, meta).`)
t.P(`// Useful outside of the Twirp server (e.g. http middleware), but does not trigger hooks.`)
t.P(`// If err is not a twirp.Error, it will get wrapped with twirp.InternalErrorWith(err)`)
t.P(`func WriteError(resp `, t.pkgs["http"], `.ResponseWriter, err error) {`)
t.P(` writeError(`, t.pkgs["context"], `.Background(), resp, err, nil)`)
t.P(`}`)
t.P()
t.P(`// writeError writes Twirp errors in the response and triggers hooks.`)
t.P(`func writeError(ctx `, t.pkgs["context"], `.Context, resp `, t.pkgs["http"], `.ResponseWriter, err error, hooks *`, t.pkgs["twirp"], `.ServerHooks) {`)
t.P(` // Convert to a twirp.Error. Non-twirp errors are converted to internal errors.`)
t.P(` var twerr `, t.pkgs["twirp"], `.Error`)
t.P(` if !`, t.pkgs["errors"], `.As(err, &twerr) {`)
t.P(` twerr = `, t.pkgs["twirp"], `.InternalErrorWith(err)`)
t.P(` }`)
t.P(` `)
t.P(` statusCode := `, t.pkgs["twirp"], `.ServerHTTPStatusFromErrorCode(twerr.Code())`)
t.P(` ctx = `, t.pkgs["ctxsetters"], `.WithStatusCode(ctx, statusCode)`)
t.P(` ctx = callError(ctx, hooks, twerr)`)
t.P(` `)
t.P(` respBody := marshalErrorToJSON(twerr)`)
t.P(` `)
t.P(` resp.Header().Set("Content-Type", "application/json") // Error responses are always JSON`)
t.P(` resp.Header().Set("Content-Length", strconv.Itoa(len(respBody)))`)
t.P(` resp.WriteHeader(statusCode) // set HTTP status code and send response`)
t.P(` `)
t.P(` _, writeErr := resp.Write(respBody)`)
t.P(` if writeErr != nil {`)
t.P(` // We have three options here. We could log the error, call the Error`)
t.P(` // hook, or just silently ignore the error.`)
t.P(` //`)
t.P(` // Logging is unacceptable because we don't have a user-controlled `)
t.P(` // logger; writing out to stderr without permission is too rude.`)
t.P(` //`)
t.P(` // Calling the Error hook would confuse users: it would mean the Error`)
t.P(` // hook got called twice for one request, which is likely to lead to`)
t.P(` // duplicated log messages and metrics, no matter how well we document`)
t.P(` // the behavior.`)
t.P(` //`)
t.P(` // Silently ignoring the error is our least-bad option. It's highly`)
t.P(` // likely that the connection is broken and the original 'err' says`)
t.P(` // so anyway.`)
t.P(` _ = writeErr`)
t.P(` }`)
t.P(` `)
t.P(` callResponseSent(ctx, hooks)`)
t.P(`}`)
t.P()
t.P(`// sanitizeBaseURL parses the the baseURL, and adds the "http" scheme if needed.`)
t.P(`// If the URL is unparsable, the baseURL is returned unchanged.`)
t.P(`func sanitizeBaseURL(baseURL string) string {`)
t.P(` u, err := `, t.pkgs["url"], `.Parse(baseURL)`)
t.P(` if err != nil {`)
t.P(` return baseURL // invalid URL will fail later when making requests`)
t.P(` }`)
t.P(` if u.Scheme == "" {`)
t.P(` u.Scheme = "http"`)
t.P(` }`)
t.P(` return u.String()`)
t.P(`}`)
t.P()
t.P(`// baseServicePath composes the path prefix for the service (without <Method>).`)
t.P(`// e.g.: baseServicePath("/twirp", "my.pkg", "MyService")`)
t.P(`// returns => "/twirp/my.pkg.MyService/"`)
t.P(`// e.g.: baseServicePath("", "", "MyService")`)
t.P(`// returns => "/MyService/"`)
t.P(`func baseServicePath(prefix, pkg, service string) string {`)
t.P(` fullServiceName := service`)
t.P(` if pkg != "" {`)
t.P(` fullServiceName = pkg + "." + service`)
t.P(` }`)
t.P(` return path.Join("/", prefix, fullServiceName) + "/"`)
t.P(`}`)
t.P()
t.P(`// parseTwirpPath extracts path components form a valid Twirp route.`)
t.P(`// Expected format: "[<prefix>]/<package>.<Service>/<Method>"`)
t.P(`// e.g.: prefix, pkgService, method := parseTwirpPath("/twirp/pkg.Svc/MakeHat")`)
t.P(`func parseTwirpPath(path string) (string, string, string) {`)
t.P(` parts := `, t.pkgs["strings"], `.Split(path, "/")`)
t.P(` if len(parts) < 2 {`)
t.P(` return "", "", ""`)
t.P(` }`)
t.P(` method := parts[len(parts)-1]`)
t.P(` pkgService := parts[len(parts)-2]`)
t.P(` prefix := `, t.pkgs["strings"], `.Join(parts[0:len(parts)-2], "/")`)
t.P(` return prefix, pkgService, method`)
t.P(`}`)
t.P()
t.P(`// getCustomHTTPReqHeaders retrieves a copy of any headers that are set in`)
t.P(`// a context through the twirp.WithHTTPRequestHeaders function.`)
t.P(`// If there are no headers set, or if they have the wrong type, nil is returned.`)
t.P(`func getCustomHTTPReqHeaders(ctx `, t.pkgs["context"], `.Context) `, t.pkgs["http"], `.Header {`)
t.P(` header, ok := `, t.pkgs["twirp"], `.HTTPRequestHeaders(ctx)`)
t.P(` if !ok || header == nil {`)
t.P(` return nil`)
t.P(` }`)
t.P(` copied := make(`, t.pkgs["http"], `.Header)`)
t.P(` for k, vv := range header {`)
t.P(` if vv == nil {`)
t.P(` copied[k] = nil`)
t.P(` continue`)
t.P(` }`)
t.P(` copied[k] = make([]string, len(vv))`)
t.P(` copy(copied[k], vv)`)
t.P(` }`)
t.P(` return copied`)
t.P(`}`)
t.P()
t.P(`// newRequest makes an http.Request from a client, adding common headers.`)
t.P(`func newRequest(ctx `, t.pkgs["context"], `.Context, url string, reqBody io.Reader, contentType string) (*`, t.pkgs["http"], `.Request, error) {`)
t.P(` req, err := `, t.pkgs["http"], `.NewRequest("POST", url, reqBody)`)
t.P(` if err != nil {`)
t.P(` return nil, err`)
t.P(` }`)
t.P(` req = req.WithContext(ctx)`)
t.P(` if customHeader := getCustomHTTPReqHeaders(ctx); customHeader != nil {`)
t.P(` req.Header = customHeader`)
t.P(` }`)
t.P(` req.Header.Set("Accept", contentType)`)
t.P(` req.Header.Set("Content-Type", contentType)`)
t.P(` req.Header.Set("Twirp-Version", "`, gen.Version, `")`)
t.P(` return req, nil`)
t.P(`}`)
t.P()
t.P(`// JSON serialization for errors`)
t.P(`type twerrJSON struct {`)
t.P(" Code string `json:\"code\"`")
t.P(" Msg string `json:\"msg\"`")
t.P(" Meta map[string]string `json:\"meta,omitempty\"`")
t.P(`}`)
t.P()
t.P(`// marshalErrorToJSON returns JSON from a twirp.Error, that can be used as HTTP error response body.`)
t.P(`// If serialization fails, it will use a descriptive Internal error instead.`)
t.P(`func marshalErrorToJSON(twerr `, t.pkgs["twirp"], `.Error) []byte {`)
t.P(` // make sure that msg is not too large`)
t.P(` msg := twerr.Msg()`)
t.P(` if len(msg) > 1e6 {`)
t.P(` msg = msg[:1e6]`)
t.P(` }`)
t.P(``)
t.P(` tj := twerrJSON{`)
t.P(` Code: string(twerr.Code()),`)
t.P(` Msg: msg,`)
t.P(` Meta: twerr.MetaMap(),`)
t.P(` }`)
t.P(``)
t.P(` buf, err := `, t.pkgs["json"], `.Marshal(&tj)`)
t.P(` if err != nil {`)
t.P(` buf = []byte("{\"type\": \"" + `, t.pkgs["twirp"], `.Internal +"\", \"msg\": \"There was an error but it could not be serialized into JSON\"}") // fallback`)
t.P(` }`)
t.P(``)
t.P(` return buf`)
t.P(`}`)
t.P()
t.P(`// errorFromResponse builds a twirp.Error from a non-200 HTTP response.`)
t.P(`// If the response has a valid serialized Twirp error, then it's returned.`)
t.P(`// If not, the response status code is used to generate a similar twirp`)
t.P(`// error. See twirpErrorFromIntermediary for more info on intermediary errors.`)
t.P(`func errorFromResponse(resp *`, t.pkgs["http"], `.Response) `, t.pkgs["twirp"], `.Error {`)
t.P(` statusCode := resp.StatusCode`)
t.P(` statusText := `, t.pkgs["http"], `.StatusText(statusCode)`)
t.P(``)
t.P(` if isHTTPRedirect(statusCode) {`)
t.P(` // Unexpected redirect: it must be an error from an intermediary.`)
t.P(` // Twirp clients don't follow redirects automatically, Twirp only handles`)
t.P(` // POST requests, redirects should only happen on GET and HEAD requests.`)
t.P(` location := resp.Header.Get("Location")`)
t.P(` msg := `, t.pkgs["fmt"], `.Sprintf("unexpected HTTP status code %d %q received, Location=%q", statusCode, statusText, location)`)
t.P(` return twirpErrorFromIntermediary(statusCode, msg, location)`)
t.P(` }`)
t.P(``)
t.P(` respBodyBytes, err := `, t.pkgs["io"], `.ReadAll(resp.Body)`)
t.P(` if err != nil {`)
t.P(` return wrapInternal(err, "failed to read server error response body")`)
t.P(` }`)
t.P(``)
t.P(` var tj twerrJSON`)
t.P(` dec := `, t.pkgs["json"], `.NewDecoder(`, t.pkgs["bytes"], `.NewReader(respBodyBytes))`)
t.P(` dec.DisallowUnknownFields()`)
t.P(` if err := dec.Decode(&tj); err != nil || tj.Code == "" {`)
t.P(` // Invalid JSON response; it must be an error from an intermediary.`)
t.P(` msg := `, t.pkgs["fmt"], `.Sprintf("Error from intermediary with HTTP status code %d %q", statusCode, statusText)`)
t.P(` return twirpErrorFromIntermediary(statusCode, msg, string(respBodyBytes))`)
t.P(` }`)
t.P(``)
t.P(` errorCode := `, t.pkgs["twirp"], `.ErrorCode(tj.Code)`)
t.P(` if !`, t.pkgs["twirp"], `.IsValidErrorCode(errorCode) {`)
t.P(` msg := "invalid type returned from server error response: "+tj.Code`)
t.P(` return `, t.pkgs["twirp"], `.InternalError(msg).WithMeta("body", string(respBodyBytes))`)
t.P(` }`)
t.P(``)
t.P(` twerr := `, t.pkgs["twirp"], `.NewError(errorCode, tj.Msg)`)
t.P(` for k, v := range(tj.Meta) {`)
t.P(` twerr = twerr.WithMeta(k, v)`)
t.P(` }`)
t.P(` return twerr`)
t.P(`}`)
t.P()
t.P(`// twirpErrorFromIntermediary maps HTTP errors from non-twirp sources to twirp errors.`)
t.P(`// The mapping is similar to gRPC: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md.`)
t.P(`// Returned twirp Errors have some additional metadata for inspection.`)
t.P(`func twirpErrorFromIntermediary(status int, msg string, bodyOrLocation string) `, t.pkgs["twirp"], `.Error {`)
t.P(` var code `, t.pkgs["twirp"], `.ErrorCode`)
t.P(` if isHTTPRedirect(status) { // 3xx`)
t.P(` code = `, t.pkgs["twirp"], `.Internal`)
t.P(` } else {`)
t.P(` switch status {`)
t.P(` case 400: // Bad Request`)
t.P(` code = `, t.pkgs["twirp"], `.Internal`)
t.P(` case 401: // Unauthorized`)
t.P(` code = `, t.pkgs["twirp"], `.Unauthenticated`)
t.P(` case 403: // Forbidden`)
t.P(` code = `, t.pkgs["twirp"], `.PermissionDenied`)
t.P(` case 404: // Not Found`)
t.P(` code = `, t.pkgs["twirp"], `.BadRoute`)
t.P(` case 429: // Too Many Requests`)
t.P(` code = `, t.pkgs["twirp"], `.ResourceExhausted`)
t.P(` case 502, 503, 504: // Bad Gateway, Service Unavailable, Gateway Timeout`)
t.P(` code = `, t.pkgs["twirp"], `.Unavailable`)
t.P(` default: // All other codes`)
t.P(` code = `, t.pkgs["twirp"], `.Unknown`)
t.P(` }`)
t.P(` }`)
t.P(``)
t.P(` twerr := `, t.pkgs["twirp"], `.NewError(code, msg)`)
t.P(` twerr = twerr.WithMeta("http_error_from_intermediary", "true") // to easily know if this error was from intermediary`)
t.P(` twerr = twerr.WithMeta("status_code", `, t.pkgs["strconv"], `.Itoa(status))`)
t.P(` if isHTTPRedirect(status) {`)
t.P(` twerr = twerr.WithMeta("location", bodyOrLocation)`)
t.P(` } else {`)
t.P(` twerr = twerr.WithMeta("body", bodyOrLocation)`)
t.P(` }`)
t.P(` return twerr`)
t.P(`}`)
t.P()
t.P(`func isHTTPRedirect(status int) bool {`)
t.P(` return status >= 300 && status <= 399`)
t.P(`}`)
t.P()
t.P(`// wrapInternal wraps an error with a prefix as an Internal error.`)
t.P(`// The original error cause is accessible by github.com/pkg/errors.Cause.`)
t.P(`func wrapInternal(err error, prefix string) `, t.pkgs["twirp"], `.Error {`)
t.P(` return `, t.pkgs["twirp"], `.InternalErrorWith(&wrappedError{prefix: prefix, cause: err})`)
t.P(`}`)
t.P(`type wrappedError struct {`)
t.P(` prefix string`)
t.P(` cause error`)
t.P(`}`)
t.P(`func (e *wrappedError) Error() string { return e.prefix + ": " + e.cause.Error() }`)
t.P(`func (e *wrappedError) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As `)
t.P(`func (e *wrappedError) Cause() error { return e.cause } // for github.com/pkg/errors`)
t.P()
t.P(`// ensurePanicResponses makes sure that rpc methods causing a panic still result in a Twirp Internal`)
t.P(`// error response (status 500), and error hooks are properly called with the panic wrapped as an error.`)
t.P(`// The panic is re-raised so it can be handled normally with middleware.`)
t.P(`func ensurePanicResponses(ctx `, t.pkgs["context"], `.Context, resp `, t.pkgs["http"], `.ResponseWriter, hooks *`, t.pkgs["twirp"], `.ServerHooks) {`)
t.P(` if r := recover(); r != nil {`)
t.P(` // Wrap the panic as an error so it can be passed to error hooks.`)
t.P(` // The original error is accessible from error hooks, but not visible in the response.`)
t.P(` err := errFromPanic(r)`)
t.P(` twerr := &internalWithCause{msg: "Internal service panic", cause: err}`)
t.P(` // Actually write the error`)
t.P(` writeError(ctx, resp, twerr, hooks)`)
t.P(` // If possible, flush the error to the wire.`)
t.P(` f, ok := resp.(`, t.pkgs["http"], `.Flusher)`)
t.P(` if ok {`)
t.P(` f.Flush()`)
t.P(` }`)
t.P(``)
t.P(` panic(r)`)
t.P(` }`)
t.P(`}`)
t.P(``)
t.P(`// errFromPanic returns the typed error if the recovered panic is an error, otherwise formats as error.`)
t.P(`func errFromPanic(p interface{}) error {`)
t.P(` if err, ok := p.(error); ok {`)
t.P(` return err`)
t.P(` }`)
t.P(` return fmt.Errorf("panic: %v", p)`)
t.P(`}`)
t.P(``)
t.P(`// internalWithCause is a Twirp Internal error wrapping an original error cause,`)
t.P(`// but the original error message is not exposed on Msg(). The original error`)
t.P(`// can be checked with go1.13+ errors.Is/As, and also by (github.com/pkg/errors).Unwrap`)
t.P(`type internalWithCause struct {`)
t.P(` msg string`)
t.P(` cause error`)
t.P(`}`)
t.P(`func (e *internalWithCause) Unwrap() error { return e.cause } // for go1.13 + errors.Is/As`)
t.P(`func (e *internalWithCause) Cause() error { return e.cause } // for github.com/pkg/errors`)
t.P(`func (e *internalWithCause) Error() string { return e.msg + ": " + e.cause.Error()}`)
t.P(`func (e *internalWithCause) Code() `, t.pkgs["twirp"], `.ErrorCode { return `, t.pkgs["twirp"], `.Internal }`)
t.P(`func (e *internalWithCause) Msg() string { return e.msg }`)
t.P(`func (e *internalWithCause) Meta(key string) string { return "" }`)
t.P(`func (e *internalWithCause) MetaMap() map[string]string { return nil }`)
t.P(`func (e *internalWithCause) WithMeta(key string, val string) `, t.pkgs["twirp"], `.Error { return e }`)
t.P()
t.P(`// malformedRequestError is used when the twirp server cannot unmarshal a request`)
t.P(`func malformedRequestError(msg string) `, t.pkgs["twirp"], `.Error {`)
t.P(` return `, t.pkgs["twirp"], `.NewError(`, t.pkgs["twirp"], `.Malformed, msg)`)
t.P(`}`)
t.P()
t.P(`// badRouteError is used when the twirp server cannot route a request`)
t.P(`func badRouteError(msg string, method, url string) `, t.pkgs["twirp"], `.Error {`)
t.P(` err := `, t.pkgs["twirp"], `.NewError(`, t.pkgs["twirp"], `.BadRoute, msg)`)
t.P(` err = err.WithMeta("twirp_invalid_route", method+" "+url)`)
t.P(` return err`)
t.P(`}`)
t.P()
t.P(`// withoutRedirects makes sure that the POST request can not be redirected.`)
t.P(`// The standard library will, by default, redirect requests (including POSTs) if it gets a 302 or`)
t.P(`// 303 response, and also 301s in go1.8. It redirects by making a second request, changing the`)
t.P(`// method to GET and removing the body. This produces very confusing error messages, so instead we`)
t.P(`// set a redirect policy that always errors. This stops Go from executing the redirect.`)
t.P(`//`)
t.P(`// We have to be a little careful in case the user-provided http.Client has its own CheckRedirect`)
t.P(`// policy - if so, we'll run through that policy first.`)
t.P(`//`)
t.P(`// Because this requires modifying the http.Client, we make a new copy of the client and return it.`)
t.P(`func withoutRedirects(in *`, t.pkgs["http"], `.Client) *`, t.pkgs["http"], `.Client {`)
t.P(` copy := *in`)
t.P(` copy.CheckRedirect = func(req *`, t.pkgs["http"], `.Request, via []*`, t.pkgs["http"], `.Request) error {`)
t.P(` if in.CheckRedirect != nil {`)
t.P(` // Run the input's redirect if it exists, in case it has side effects, but ignore any error it`)
t.P(` // returns, since we want to use ErrUseLastResponse.`)
t.P(` err := in.CheckRedirect(req, via)`)
t.P(` _ = err // Silly, but this makes sure generated code passes errcheck -blank, which some people use.`)
t.P(` }`)
t.P(` return `, t.pkgs["http"], `.ErrUseLastResponse`)
t.P(` }`)
t.P(` return ©`)
t.P(`}`)
t.P()
t.P(`// doProtobufRequest makes a Protobuf request to the remote Twirp service.`)
t.P(`func doProtobufRequest(ctx `, t.pkgs["context"], `.Context, client HTTPClient, hooks *`, t.pkgs["twirp"], `.ClientHooks, url string, in, out `, t.pkgs["proto"], `.Message) (_ `, t.pkgs["context"], `.Context, err error) {`)
t.P(` reqBodyBytes, err := `, t.pkgs["proto"], `.Marshal(in)`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to marshal proto request")`)
t.P(` }`)
t.P(` reqBody := `, t.pkgs["bytes"], `.NewBuffer(reqBodyBytes)`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P()
t.P(` req, err := newRequest(ctx, url, reqBody, "application/protobuf")`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "could not build request")`)
t.P(` }`)
t.P(` ctx, err = callClientRequestPrepared(ctx, hooks, req)`)
t.P(` if err != nil {`)
t.P(` return ctx, err`)
t.P(` }`)
t.P()
t.P(` req = req.WithContext(ctx)`)
t.P(` resp, err := client.Do(req)`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to do request")`)
t.P(` }`)
t.P(` defer func() { _ = resp.Body.Close() }()`)
t.P()
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P()
t.P(` if resp.StatusCode != 200 {`)
t.P(` return ctx, errorFromResponse(resp)`)
t.P(` }`)
t.P()
t.P(` respBodyBytes, err := `, t.pkgs["io"], `.ReadAll(resp.Body)`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to read response body")`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P()
t.P(` if err = `, t.pkgs["proto"], `.Unmarshal(respBodyBytes, out); err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to unmarshal proto response")`)
t.P(` }`)
t.P(` return ctx, nil`)
t.P(`}`)
t.P()
t.P(`// doJSONRequest makes a JSON request to the remote Twirp service.`)
t.P(`func doJSONRequest(ctx `, t.pkgs["context"], `.Context, client HTTPClient, hooks *`, t.pkgs["twirp"], `.ClientHooks, url string, in, out `, t.pkgs["proto"], `.Message) (_ `, t.pkgs["context"], `.Context, err error) {`)
t.P(` marshaler := &`, t.pkgs["protojson"], `.MarshalOptions{UseProtoNames: true}`)
t.P(` reqBytes, err := marshaler.Marshal(in)`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to marshal json request")`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P()
t.P(` req, err := newRequest(ctx, url, `, t.pkgs["bytes"], `.NewReader(reqBytes), "application/json")`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "could not build request")`)
t.P(` }`)
t.P(` ctx, err = callClientRequestPrepared(ctx, hooks, req)`)
t.P(` if err != nil {`)
t.P(` return ctx, err`)
t.P(` }`)
t.P()
t.P(` req = req.WithContext(ctx)`)
t.P(` resp, err := client.Do(req)`)
t.P(` if err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to do request")`)
t.P(` }`)
t.P()
t.P(` defer func() {`)
t.P(` cerr := resp.Body.Close()`)
t.P(` if err == nil && cerr != nil {`)
t.P(` err = wrapInternal(cerr, "failed to close response body")`)
t.P(` }`)
t.P(` }()`)
t.P()
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P()
t.P(` if resp.StatusCode != 200 {`)
t.P(` return ctx, errorFromResponse(resp)`)
t.P(` }`)
t.P()
t.P(` d := `, t.pkgs["json"], `.NewDecoder(resp.Body)`)
t.P(` rawRespBody := `, t.pkgs["json"], `.RawMessage{}`)
t.P(` if err := d.Decode(&rawRespBody); err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to unmarshal json response")`)
t.P(` }`)
t.P(` unmarshaler := `, t.pkgs["protojson"], `.UnmarshalOptions{DiscardUnknown: true}`)
t.P(` if err = unmarshaler.Unmarshal(rawRespBody, out); err != nil {`)
t.P(` return ctx, wrapInternal(err, "failed to unmarshal json response")`)
t.P(` }`)
t.P(` if err = ctx.Err(); err != nil {`)
t.P(` return ctx, wrapInternal(err, "aborted because context was done")`)
t.P(` }`)
t.P(` return ctx, nil`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.RequestReceived if the hook is available`)
t.P(`func callRequestReceived(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) (`, t.pkgs["context"], `.Context, error) {`)
t.P(` if h == nil || h.RequestReceived == nil {`)
t.P(` return ctx, nil`)
t.P(` }`)
t.P(` return h.RequestReceived(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.RequestRouted if the hook is available`)
t.P(`func callRequestRouted(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) (`, t.pkgs["context"], `.Context, error) {`)
t.P(` if h == nil || h.RequestRouted == nil {`)
t.P(` return ctx, nil`)
t.P(` }`)
t.P(` return h.RequestRouted(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.ResponsePrepared if the hook is available`)
t.P(`func callResponsePrepared(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) `, t.pkgs["context"], `.Context {`)
t.P(` if h == nil || h.ResponsePrepared == nil {`)
t.P(` return ctx`)
t.P(` }`)
t.P(` return h.ResponsePrepared(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.ResponseSent if the hook is available`)
t.P(`func callResponseSent(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks) {`)
t.P(` if h == nil || h.ResponseSent == nil {`)
t.P(` return`)
t.P(` }`)
t.P(` h.ResponseSent(ctx)`)
t.P(`}`)
t.P()
t.P(`// Call twirp.ServerHooks.Error if the hook is available`)
t.P(`func callError(ctx `, t.pkgs["context"], `.Context, h *`, t.pkgs["twirp"], `.ServerHooks, err `, t.pkgs["twirp"], `.Error) `, t.pkgs["context"], `.Context {`)
t.P(` if h == nil || h.Error == nil {`)
t.P(` return ctx`)
t.P(` }`)
t.P(` return h.Error(ctx, err)`)
t.P(`}`)
t.P()
t.generateClientHooks()
}
// P forwards to g.gen.P, which prints output.
func (t *twirp) P(args ...string) {
for _, v := range args {
t.output.WriteString(v)
}
t.output.WriteByte('\n')
}
// Big header comments to makes it easier to visually parse a generated file.
func (t *twirp) sectionComment(sectionTitle string) {
t.P()
t.P(`// `, strings.Repeat("=", len(sectionTitle)))
t.P(`// `, sectionTitle)
t.P(`// `, strings.Repeat("=", len(sectionTitle)))
t.P()
}
func (t *twirp) generateService(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto, index int) {
servName := serviceNameCamelCased(service)
t.sectionComment(servName + ` Interface`)
t.generateTwirpInterface(file, service)
t.sectionComment(servName + ` Protobuf Client`)
t.generateClient("Protobuf", file, service)
t.sectionComment(servName + ` JSON Client`)
t.generateClient("JSON", file, service)
// Server
t.sectionComment(servName + ` Server Handler`)
t.generateServer(file, service)
}
func (t *twirp) generateTwirpInterface(file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) {
servName := serviceNameCamelCased(service)
comments, err := t.reg.ServiceComments(file, service)
if err == nil {
t.printComments(comments)
}
t.P(`type `, servName, ` interface {`)
for _, method := range service.Method {
comments, err = t.reg.MethodComments(file, service, method)
if err == nil {
t.printComments(comments)
}
t.P(t.generateSignature(method))
t.P()
}
t.P(`}`)
}
func (t *twirp) generateSignature(method *descriptor.MethodDescriptorProto) string {
methName := methodNameCamelCased(method)
inputType := t.goTypeName(method.GetInputType())
outputType := t.goTypeName(method.GetOutputType())
return fmt.Sprintf(` %s(%s.Context, *%s) (*%s, error)`, methName, t.pkgs["context"], inputType, outputType)
}
// valid names: 'JSON', 'Protobuf'
func (t *twirp) generateClient(name string, file *descriptor.FileDescriptorProto, service *descriptor.ServiceDescriptorProto) {
servPkg := pkgName(file)
servName := serviceNameCamelCased(service)
structName := unexported(servName) + name + "Client"
newClientFunc := "New" + servName + name + "Client"
servNameLit := serviceNameLiteral(service)
servNameCc := servName
methCnt := strconv.Itoa(len(service.Method))
t.P(`type `, structName, ` struct {`)
t.P(` client HTTPClient`)
t.P(` urls [`, methCnt, `]string`)
t.P(` interceptor `, t.pkgs["twirp"], `.Interceptor`)
t.P(` opts `, t.pkgs["twirp"], `.ClientOptions`)
t.P(`}`)
t.P()
t.P(`// `, newClientFunc, ` creates a `, name, ` client that implements the `, servName, ` interface.`)
t.P(`// It communicates using `, name, ` and can be configured with a custom HTTPClient.`)