diff --git a/.golangci.yaml b/.golangci.yaml index 63205f5..1cc947c 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -84,12 +84,12 @@ linters: #- gochecknoglobals # check that no global variables exist [fast: true, auto-fix: false] #- gochecknoinits # Checks that no init functions are present in Go code [fast: true, auto-fix: false] #- gocognit # Computes and checks the cognitive complexity of functions [fast: true, auto-fix: false] - - goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] + #- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false] - gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false] #- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false] #- godot # Check if comments end in a period [fast: true, auto-fix: true] #- godox # Tool for detection of FIXME, TODO and other comment keywords [fast: true, auto-fix: false] - - goerr113 # Golang linter to check the errors handling expressions [fast: false, auto-fix: false] + #- goerr113 # Golang linter to check the errors handling expressions [fast: false, auto-fix: false] - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true] #- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true] - goheader # Checks is file header matches to pattern [fast: true, auto-fix: false] @@ -106,7 +106,7 @@ linters: - maintidx # maintidx measures the maintainability index of each function. [fast: true, auto-fix: false] - makezero # Finds slice declarations with non-zero initial length [fast: false, auto-fix: false] - misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true] - - nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false] + #- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false] #- nestif # Reports deeply nested if statements [fast: true, auto-fix: false] - nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false] - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. [fast: false, auto-fix: false] @@ -117,7 +117,7 @@ linters: - nosnakecase # nosnakecase is a linter that detects snake case of variable naming and function name. [fast: true, auto-fix: false] - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. [fast: true, auto-fix: false] #- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test [fast: false, auto-fix: false] - - prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false] + #- prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false] - predeclared # find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false] - promlinter # Check Prometheus metrics naming via promlint [fast: true, auto-fix: false] - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false] @@ -125,13 +125,13 @@ linters: - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false] - structcheck # Finds unused struct fields [fast: false, auto-fix: false] - stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false] - - tagliatelle # Checks the struct tags. [fast: true, auto-fix: false] + #- tagliatelle # Checks the struct tags. [fast: true, auto-fix: false] - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false] - - testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false] + #- testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false] - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false] - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false] - unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false] - - unparam # Reports unused function parameters [fast: false, auto-fix: false] + #- unparam # Reports unused function parameters [fast: false, auto-fix: false] - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. [fast: true, auto-fix: false] #- varnamelen # checks that the length of a variable's name matches its scope [fast: false, auto-fix: false] - wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false] diff --git a/Makefile b/Makefile index 80ad81f..0d1f2c3 100644 --- a/Makefile +++ b/Makefile @@ -55,7 +55,7 @@ $(foreach p,$(EXAMPLES),$(eval $(call examples,$(p)))) ## Run go mod tidy recursive .PHONY: lint lint: - # @golangci-lint run + @golangci-lint run @for name in example/*/; do\ if [ $$name != "example/node_modules/" ]; then \ echo "-------- $${name} ------------";\ @@ -63,6 +63,16 @@ lint: fi \ done +.PHONY: lint.fix +lint.fix: + @golangci-lint run --fix + @for name in example/*/; do\ + if [ $$name != "example/node_modules/" ]; then \ + echo "-------- $${name} ------------";\ + sh -c "cd $$(pwd)/$${name} && golangci-lint run --fix";\ + fi \ + done + ## Run go mod tidy recursive .PHONY: gomod gomod: diff --git a/build.go b/build.go index d70ef11..739574c 100644 --- a/build.go +++ b/build.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "go/format" - "io/ioutil" "os" "path" "path/filepath" @@ -20,7 +19,7 @@ import ( func deriveCommonJSMapping(conf *config.Config) { replacer := strings.NewReplacer(".", "_", "/", "_", "-", "_") for _, mapping := range conf.Mappings { - mapping.TypeScriptModule = replacer.Replace(mapping.GoPackage) //strings.Replace(strings.Replace(mapping.GoPackage, ".", "_", -1), "/", "_", -1) + mapping.TypeScriptModule = replacer.Replace(mapping.GoPackage) } } @@ -59,8 +58,7 @@ func getPathForTarget(gomod config.Namespace, goPath string, target *config.Targ } } -func Build(conf *config.Config, goPath string) { - +func Build(conf *config.Config, goPath string) { //nolint:maintidx deriveCommonJSMapping(conf) mappedTypeScript := map[string]map[string]*code{} @@ -125,7 +123,7 @@ func Build(conf *config.Config, goPath string) { pkgName, services, structs, scalars, constantTypes, err := Read(goPaths, conf.Module, packageName, target.Services, missingTypes, missingConstants) if err != nil { - _, _ = fmt.Fprintln(os.Stderr, "\t an error occured while trying to understand your code: ", err) + _, _ = fmt.Fprintln(os.Stderr, "\t an error occurred while trying to understand your code: ", err) os.Exit(2) } @@ -179,7 +177,7 @@ func Build(conf *config.Config, goPath string) { ) // write code into file for debugging - writeErr := ioutil.WriteFile(filename, []byte(code), 0644) + writeErr := os.WriteFile(filename, []byte(code), 0644) if writeErr != nil { _, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr) os.Exit(5) @@ -189,7 +187,7 @@ func Build(conf *config.Config, goPath string) { os.Exit(5) } - writeErr := ioutil.WriteFile(filename, codeBytes, 0644) + writeErr := os.WriteFile(filename, codeBytes, 0644) if writeErr != nil { _, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr) os.Exit(5) @@ -238,9 +236,7 @@ func Build(conf *config.Config, goPath string) { _, _ = fmt.Fprintln(os.Stderr, "building structs for go package", goPackage, "to ts module", mapping.TypeScriptModule, "in file", mapping.Out) moduleCode := newCode(" ") - structIndent := -1 - - structIndent = -3 + structIndent := -3 commonJSImports(conf, moduleCode, mapping.Out) @@ -251,7 +247,6 @@ func Build(conf *config.Config, goPath string) { } sort.Strings(structNames) for _, structName := range structNames { - structCode, ok := mappedStructsMap[structName] if ok { moduleCode.app(structCode.ind(structIndent).l("").string()) @@ -264,7 +259,6 @@ func Build(conf *config.Config, goPath string) { _, _ = fmt.Fprintln(os.Stderr, " failed to update code in", mapping.Out, updateErr) } } - } func updateCode(file string, code string) error { @@ -281,10 +275,10 @@ func updateCode(file string, code string) error { if errMkdirAll != nil { return errMkdirAll } - oldCode, _ := ioutil.ReadFile(file) + oldCode, _ := os.ReadFile(file) if string(oldCode) != code { fmt.Println(" writing file", file) - return ioutil.WriteFile(file, []byte(code), 0644) + return os.WriteFile(file, []byte(code), 0644) } fmt.Println(" update file not necessary - unchanged", file) return nil diff --git a/client.go b/client.go index 3c4ff45..aee324c 100644 --- a/client.go +++ b/client.go @@ -4,7 +4,7 @@ import ( "bytes" "context" "fmt" - "io/ioutil" + "io" "net/http" "github.com/pkg/errors" @@ -31,7 +31,7 @@ func NewClient() Client { return &bufferedClient{client: defaultHttpFactory(), handle: getHandleForEncoding(EncodingMsgpack), headers: nil} } -func NewClientWithHttpClient(client *http.Client) Client { +func NewClientWithHttpClient(client *http.Client) Client { //nolint:stylecheck if client != nil { return &bufferedClient{client: client, handle: getHandleForEncoding(EncodingMsgpack), headers: nil} } else { @@ -43,7 +43,7 @@ func newRequest(ctx context.Context, url string, contentType string, buffer *byt if buffer == nil { buffer = &bytes.Buffer{} } - request, errRequest := http.NewRequestWithContext(ctx, "POST", url, buffer) + request, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, buffer) if errRequest != nil { return nil, errors.Wrap(errRequest, "could not create a request") } @@ -71,7 +71,7 @@ func (c *bufferedClient) SetClientEncoding(encoding ClientEncoding) { c.handle = getHandleForEncoding(encoding) } -func (c *bufferedClient) SetTransportHttpClient(client *http.Client) { +func (c *bufferedClient) SetTransportHttpClient(client *http.Client) { //nolint:stylecheck c.client = client } @@ -105,7 +105,7 @@ func (c *bufferedClient) Call(ctx context.Context, url string, endpoint string, // Check status if resp.StatusCode != http.StatusOK { var msg string - if value, err := ioutil.ReadAll(resp.Body); err != nil { + if value, err := io.ReadAll(resp.Body); err != nil { msg = "failed to read response body: " + err.Error() } else { msg = string(value) diff --git a/cmd/gotsrpc/gotsrpc.go b/cmd/gotsrpc/gotsrpc.go index 9ea5391..0bb42a3 100644 --- a/cmd/gotsrpc/gotsrpc.go +++ b/cmd/gotsrpc/gotsrpc.go @@ -19,8 +19,8 @@ func usage() { fmt.Println(os.Args[0], " path/to/build-config.yml") flag.PrintDefaults() } -func main() { +func main() { flagDebug := flag.Bool("debug", false, "debug") flag.Parse() diff --git a/config/config.go b/config/config.go index f193e18..d84cec9 100644 --- a/config/config.go +++ b/config/config.go @@ -2,7 +2,6 @@ package config import ( "errors" - "io/ioutil" "os" "path" "path/filepath" @@ -65,7 +64,7 @@ type Config struct { } func LoadConfigFile(file string) (conf *Config, err error) { - yamlBytes, readErr := ioutil.ReadFile(file) + yamlBytes, readErr := os.ReadFile(file) if readErr != nil { return nil, errors.New("could not read config file: " + readErr.Error()) } @@ -81,7 +80,7 @@ func LoadConfigFile(file string) (conf *Config, err error) { } conf.Module.Path = absPath - if data, err := ioutil.ReadFile(path.Join(absPath, "go.mod")); err != nil && !os.IsNotExist(err) { + if data, err := os.ReadFile(path.Join(absPath, "go.mod")); err != nil && !os.IsNotExist(err) { return nil, err } else if err == nil { modFile, err := modfile.Parse(path.Join(absPath, "go.mod"), data, nil) diff --git a/config/config_test.go b/config/config_test.go index 7054e21..b106e78 100644 --- a/config/config_test.go +++ b/config/config_test.go @@ -66,7 +66,6 @@ func TestLoadConfig(t *testing.T) { if demoTarget.Services["/service/demo"] != "Service" { t.Fatal("first service is wrong") } - } func TestLoadConfigFile_GomodAbsolute(t *testing.T) { diff --git a/error.go b/error.go index 62aaf30..7f5dbb5 100644 --- a/error.go +++ b/error.go @@ -21,12 +21,12 @@ type Error struct { // NewError returns a new instance func NewError(err error) *Error { // check if already transformed - if v, ok := err.(*Error); ok { + if v, ok := err.(*Error); ok { //nolint:errorlint return v } // skip *withStack error type - if _, ok := err.(interface { + if _, ok := err.(interface { //nolint:errorlint StackTrace() errors.StackTrace }); ok && errors.Unwrap(err) != nil { err = errors.Unwrap(err) @@ -87,7 +87,7 @@ func (e *Error) Format(s fmt.State, verb rune) { } fallthrough case 's', 'q': - io.WriteString(s, e.Error()) + _, _ = io.WriteString(s, e.Error()) } } diff --git a/example/basic/service/gorpc_gen.go b/example/basic/service/gorpc_gen.go index bc7cd0d..7127c6a 100644 --- a/example/basic/service/gorpc_gen.go +++ b/example/basic/service/gorpc_gen.go @@ -854,7 +854,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res retUIntTypeMapTyped_0 := p.service.UIntTypeMapTyped(req.V) response = ServiceUIntTypeMapTypedResponse{RetUIntTypeMapTyped_0: retUIntTypeMapTyped_0} default: - fmt.Println("Unkown request type", reflect.TypeOf(request).String()) + fmt.Println("Unknown request type", reflect.TypeOf(request).String()) } if p.callStatsHandler != nil { diff --git a/example/basic/service/gotsrpc_gen.go b/example/basic/service/gotsrpc_gen.go index a5e242a..cb4cfe8 100644 --- a/example/basic/service/gotsrpc_gen.go +++ b/example/basic/service/gotsrpc_gen.go @@ -4,7 +4,6 @@ package service import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -99,7 +98,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/errors/service/backend/gotsrpc_gen.go b/example/errors/service/backend/gotsrpc_gen.go index f946efe..efe58fb 100644 --- a/example/errors/service/backend/gotsrpc_gen.go +++ b/example/errors/service/backend/gotsrpc_gen.go @@ -4,7 +4,6 @@ package backend import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -49,7 +48,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/errors/service/frontend/gotsrpc_gen.go b/example/errors/service/frontend/gotsrpc_gen.go index a141d48..64320fd 100644 --- a/example/errors/service/frontend/gotsrpc_gen.go +++ b/example/errors/service/frontend/gotsrpc_gen.go @@ -4,7 +4,6 @@ package frontend import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -44,7 +43,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/monitor/service/gorpc_gen.go b/example/monitor/service/gorpc_gen.go index 693fb60..4ed6ffe 100644 --- a/example/monitor/service/gorpc_gen.go +++ b/example/monitor/service/gorpc_gen.go @@ -77,7 +77,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res retHello_0 := p.service.Hello(req.V) response = ServiceHelloResponse{RetHello_0: retHello_0} default: - fmt.Println("Unkown request type", reflect.TypeOf(request).String()) + fmt.Println("Unknown request type", reflect.TypeOf(request).String()) } if p.callStatsHandler != nil { diff --git a/example/monitor/service/gotsrpc_gen.go b/example/monitor/service/gotsrpc_gen.go index c3fe739..322e44e 100644 --- a/example/monitor/service/gotsrpc_gen.go +++ b/example/monitor/service/gotsrpc_gen.go @@ -4,7 +4,6 @@ package service import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -39,7 +38,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/nullable/service/gorpc_gen.go b/example/nullable/service/gorpc_gen.go index 26a2481..b2360b4 100644 --- a/example/nullable/service/gorpc_gen.go +++ b/example/nullable/service/gorpc_gen.go @@ -174,7 +174,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res r1, r2, r3, r4 := p.service.VariantH(nil, nil, req.I1, req.I2, req.I3, req.I4) response = ServiceVariantHResponse{R1: r1, R2: r2, R3: r3, R4: r4} default: - fmt.Println("Unkown request type", reflect.TypeOf(request).String()) + fmt.Println("Unknown request type", reflect.TypeOf(request).String()) } if p.callStatsHandler != nil { diff --git a/example/nullable/service/gotsrpc_gen.go b/example/nullable/service/gotsrpc_gen.go index 8627392..955b990 100644 --- a/example/nullable/service/gotsrpc_gen.go +++ b/example/nullable/service/gotsrpc_gen.go @@ -4,7 +4,6 @@ package service import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -46,7 +45,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/time/service/gorpc_gen.go b/example/time/service/gorpc_gen.go index c4c18e8..0387ec7 100644 --- a/example/time/service/gorpc_gen.go +++ b/example/time/service/gorpc_gen.go @@ -90,7 +90,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res retTimeStruct_0 := p.service.TimeStruct(req.V) response = ServiceTimeStructResponse{RetTimeStruct_0: retTimeStruct_0} default: - fmt.Println("Unkown request type", reflect.TypeOf(request).String()) + fmt.Println("Unknown request type", reflect.TypeOf(request).String()) } if p.callStatsHandler != nil { diff --git a/example/time/service/gotsrpc_gen.go b/example/time/service/gotsrpc_gen.go index 227e507..013fe2a 100644 --- a/example/time/service/gotsrpc_gen.go +++ b/example/time/service/gotsrpc_gen.go @@ -4,7 +4,6 @@ package service import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -40,7 +39,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/example/union/service/gotsrpc_gen.go b/example/union/service/gotsrpc_gen.go index 76e9c8e..fb13315 100644 --- a/example/union/service/gotsrpc_gen.go +++ b/example/union/service/gotsrpc_gen.go @@ -4,7 +4,6 @@ package service import ( io "io" - ioutil "io/ioutil" http "net/http" time "time" @@ -47,7 +46,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body funcName := gotsrpc.GetCalledFunc(r, p.EndPoint) callStats, _ := gotsrpc.GetStatsForRequest(r) diff --git a/go.go b/go.go index e802a8f..c5949fd 100644 --- a/go.go +++ b/go.go @@ -22,7 +22,7 @@ func (v *Value) goType(aliases map[string]string, packageName string) (t string) if v.IsPtr { t = "*" } - switch true { + switch { case v.Array != nil: t += "[]" + v.Array.Value.goType(aliases, packageName) case len(v.GoScalarType) > 0: @@ -49,80 +49,6 @@ func (v *Value) goType(aliases map[string]string, packageName string) (t string) return } -func (v *Value) emptyLiteral(aliases map[string]string) (e string) { - e = "" - if v.IsPtr { - e += "&" - } - switch true { - case v.Map != nil: - e += "map[" + v.Map.KeyGoType + "]" + v.Map.Value.emptyLiteral(aliases) - case len(v.GoScalarType) > 0: - switch v.GoScalarType { - case "string": - e += "\"\"" - case "float": - return "float(0.0)" - case "float32": - return "float32(0.0)" - case "float64": - return "float64(0.0)" - case "int": - return "int(0)" - case "int8": - return "int8(0)" - case "int16": - return "int16(0)" - case "int32": - return "int32(0)" - case "int64": - return "int64(0)" - case "uint": - return "uint(0)" - case "uint8": - return "uint8(0)" - case "uint16": - return "uint16(0)" - case "uint32": - return "uint32(0)" - case "uint64": - return "uint64(0)" - case "bool": - return "false" - } - case v.Array != nil: - e += "[]" - if v.Array.Value.IsPtr { - e += "*" - } - l := v.Array.Value.emptyLiteral(aliases) - if len(v.Array.Value.GoScalarType) == 0 { - if v.Array.Value.IsPtr { - l = strings.TrimPrefix(l, "&") - } - l = strings.TrimSuffix(l, "{}") - } else { - l = v.Array.Value.GoScalarType - } - e += l + "{}" - case v.StructType != nil: - alias := aliases[v.StructType.Package] - if alias != "" { - e += alias + "." - } - e += v.StructType.Name + "{}" - case v.Scalar != nil: - alias := aliases[v.Scalar.Package] - if alias != "" { - e += alias + "." - } - e += v.Scalar.Name + "{}" - case v.IsInterface: - e += "interface{}{}" - } - return -} - func lcfirst(str string) string { return strfirst(str, strings.ToLower) } @@ -139,7 +65,6 @@ func strfirst(str string, strfunc func(string) string) string { } else { res += string(char) } - } return res } @@ -147,12 +72,11 @@ func strfirst(str string, strfunc func(string) string) string { func extractImport(packageName string, fullPackageName string, aliases map[string]string) { r := strings.NewReplacer(".", "_", "/", "_", "-", "_") if packageName != fullPackageName { - alias, ok := aliases[packageName] - if !ok { + if _, ok := aliases[packageName]; !ok { packageParts := strings.Split(packageName, "/") beautifulAlias := packageParts[len(packageParts)-1] uglyAlias := r.Replace(packageName) - alias = uglyAlias //beautifulAlias + alias := uglyAlias // beautifulAlias for _, otherAlias := range aliases { if otherAlias == beautifulAlias { alias = uglyAlias @@ -189,7 +113,6 @@ func renderTSRPCServiceProxies(services ServiceList, fullPackageName string, pac "time": "time", "net/http": "http", "io": "io", - "io/ioutil": "ioutil", "github.com/foomo/gotsrpc/v2": "gotsrpc", } for _, service := range services { @@ -256,7 +179,7 @@ func renderTSRPCServiceProxies(services ServiceList, fullPackageName string, pac gotsrpc.ErrorMethodNotAllowed(w) return } - defer io.Copy(ioutil.Discard, r.Body) // Drain Request Body + defer io.Copy(io.Discard, r.Body) // Drain Request Body `) g.l("funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)") @@ -435,7 +358,7 @@ func renderTSRPCServiceClients(services ServiceList, fullPackageName string, pac interfaceName := service.Name + "GoTSRPCClient" clientName := "HTTP" + interfaceName - //Render Interface + // Render Interface g.l(`type ` + interfaceName + ` interface { `) for _, method := range service.Methods { ms := newMethodSignature(method, aliases, fullPackageName) @@ -444,7 +367,7 @@ func renderTSRPCServiceClients(services ServiceList, fullPackageName string, pac g.l(`} `) - //Render Constructors + // Render Constructors g.l(` type ` + clientName + ` struct { URL string @@ -634,7 +557,7 @@ func renderGoRPCServiceProxies(services ServiceList, fullPackageName string, pac g.l(`response = ` + service.Name + method.Name + `Response{` + strings.Join(retParams, ", ") + `}`) } g.l(`default:`) - g.l(`fmt.Println("Unkown request type", reflect.TypeOf(request).String())`) + g.l(`fmt.Println("Unknown request type", reflect.TypeOf(request).String())`) g.l(`}`) g.nl() g.l(`if p.callStatsHandler != nil {`) diff --git a/gotsrpc.go b/gotsrpc.go index 82a720b..78fcd73 100644 --- a/gotsrpc.go +++ b/gotsrpc.go @@ -21,7 +21,9 @@ import ( "github.com/foomo/gotsrpc/v2/config" ) -const contextStatsKey = "gotsrpcStats" +type contextKey string + +const contextStatsKey contextKey = "gotsrpcStats" func GetCalledFunc(r *http.Request, endPoint string) string { return strings.TrimPrefix(r.URL.Path, endPoint+"/") @@ -71,8 +73,8 @@ func RequestWithStatsContext(r *http.Request) *http.Request { } func GetStatsForRequest(r *http.Request) (*CallStats, bool) { - if value := r.Context().Value(contextStatsKey); value != nil { - return value.(*CallStats), true + if value, ok := r.Context().Value(contextStatsKey).(*CallStats); ok && value != nil { + return value, true } else { return &CallStats{}, false } @@ -197,9 +199,7 @@ func parsePackage(goPaths []string, gomod config.Namespace, packageName string) } var foundPackages []string sortedGoPaths := make([]string, len(goPaths)) - for iGoPath := range goPaths { - sortedGoPaths[iGoPath] = goPaths[iGoPath] - } + copy(sortedGoPaths, goPaths) sort.Sort(byLen(sortedGoPaths)) var parsedPkg *ast.Package diff --git a/http.go b/http.go index 1cc6c53..e37fd22 100644 --- a/http.go +++ b/http.go @@ -9,7 +9,7 @@ import ( // Default Client Factory // https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779 -var defaultHttpFactory HttpClientFactory = func() *http.Client { +var defaultHttpFactory HttpClientFactory = func() *http.Client { //nolint:stylecheck transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ @@ -28,8 +28,8 @@ var defaultHttpFactory HttpClientFactory = func() *http.Client { } } -type HttpClientFactory func() *http.Client +type HttpClientFactory func() *http.Client //nolint:stylecheck -func SetDefaultHttpClientFactory(factory HttpClientFactory) { +func SetDefaultHttpClientFactory(factory HttpClientFactory) { //nolint:stylecheck defaultHttpFactory = factory } diff --git a/http_test.go b/http_test.go index 2aeff7e..61f7a3c 100644 --- a/http_test.go +++ b/http_test.go @@ -1,9 +1,10 @@ package gotsrpc import ( - "github.com/stretchr/testify/assert" "net/http" "testing" + + "github.com/stretchr/testify/assert" ) func TestSetDefaultHttpClientFactory(t *testing.T) { diff --git a/instrumentation_test.go b/instrumentation_test.go index c36608b..7645fb5 100644 --- a/instrumentation_test.go +++ b/instrumentation_test.go @@ -10,12 +10,11 @@ import ( func TestInstrumentedService(t *testing.T) { middleware := func(w http.ResponseWriter, r *http.Request) { - if s := GetStatsForRequest(r); s != nil { + if s, ok := GetStatsForRequest(r); ok && s != nil { s.Func = "func" s.Package = "package" s.Service = "service" } - return } t.Run("stats", func(t *testing.T) { @@ -29,7 +28,7 @@ func TestInstrumentedService(t *testing.T) { }) rsp := httptest.NewRecorder() - req := httptest.NewRequest("GET", "/test", nil) + req := httptest.NewRequest(http.MethodGet, "/test", nil) handler(rsp, req) diff --git a/model.go b/model.go index 6da9725..0d51681 100644 --- a/model.go +++ b/model.go @@ -71,24 +71,6 @@ func (sm ServiceMethods) Len() int { return len(sm) } func (sm ServiceMethods) Swap(i, j int) { sm[i], sm[j] = sm[j], sm[i] } func (sm ServiceMethods) Less(i, j int) bool { return sm[i].Name < sm[j].Name } -func (sm ServiceMethods) getMethodByName(name string) *Method { - for _, m := range sm { - if m.Name == name { - return m - } - } - return nil -} - -func (sl ServiceList) getServiceByName(name string) *Service { - for _, s := range sl { - if s.Name == name { - return s - } - } - return nil -} - type Method struct { Name string Args []*Field diff --git a/prometheus/prometheus.go b/prometheus/prometheus.go index 4d18fcc..6cb2862 100644 --- a/prometheus/prometheus.go +++ b/prometheus/prometheus.go @@ -3,12 +3,13 @@ package prometheus import ( "net/http" - "github.com/foomo/gotsrpc/v2" p "github.com/prometheus/client_golang/prometheus" + + "github.com/foomo/gotsrpc/v2" ) func InstrumentService(s http.HandlerFunc) (handler http.HandlerFunc) { - requestDuration := p.NewSummaryVec(p.SummaryOpts{ + requestDuration := p.NewSummaryVec(p.SummaryOpts{ //nolint:promlinter Namespace: "gotsrpc", Subsystem: "service", Name: "time_nanoseconds", diff --git a/reader_test.go b/reader_test.go deleted file mode 100644 index c74f60f..0000000 --- a/reader_test.go +++ /dev/null @@ -1,35 +0,0 @@ -package gotsrpc - -import ( - "github.com/foomo/gotsrpc/v2/config" - "os" - "testing" - - "github.com/stretchr/testify/assert" -) - -func getTestServiceList(t *testing.T) ServiceList { - // ReaderTrace = true - serviceMap := map[string]string{ - "/demo": "Demo", - } - - packageName := "github.com/foomo/gotsrpc/v2/demo" - - pkg, parseErr := parsePackage([]string{os.Getenv("GOPATH")}, config.Namespace{}, packageName) - assert.NoError(t, parseErr) - - services, err := readServicesInPackage(pkg, packageName, serviceMap) - assert.NoError(t, err) - - missingTypes := map[string]bool{} - for _, s := range services { - for _, m := range s.Methods { - collectStructTypes(m.Return, missingTypes) - collectStructTypes(m.Args, missingTypes) - collectScalarTypes(m.Return, missingTypes) - collectScalarTypes(m.Args, missingTypes) - } - } - return services -} diff --git a/servicereader.go b/servicereader.go index 3d5a7c0..4c0171a 100644 --- a/servicereader.go +++ b/servicereader.go @@ -34,11 +34,8 @@ func readServiceFile(file *ast.File, packageName string, services ServiceList) e trace("that is a method named", funcDecl.Name) if len(funcDecl.Recv.List) == 1 { firstReceiverField := funcDecl.Recv.List[0] - if "*ast.StarExpr" == reflect.ValueOf(firstReceiverField.Type).Type().String() { - starExpr := firstReceiverField.Type.(*ast.StarExpr) - if "*ast.Ident" == reflect.ValueOf(starExpr.X).Type().String() { - - ident := starExpr.X.(*ast.Ident) + if starExpr, ok := firstReceiverField.Type.(*ast.StarExpr); ok { + if ident, ok := starExpr.X.(*ast.Ident); ok { service, ok := findService(ident.Name) firstCharOfMethodName := funcDecl.Name.Name[0:1] if !ok || strings.ToLower(firstCharOfMethodName) == firstCharOfMethodName { @@ -77,7 +74,7 @@ func readServiceFile(file *ast.File, packageName string, services ServiceList) e } mname := fieldDecl.Names[0] trace(" on sth:", mname.Name) - //fmt.Println("interface:", ident.Name, "method:", mname.Name) + // fmt.Println("interface:", ident.Name, "method:", mname.Name) service.Methods = append(service.Methods, &Method{ Name: mname.Name, Args: readFields(funcDecl.Params, fileImports), @@ -121,13 +118,11 @@ func standardImportName(importPath string) string { func getFileImports(file *ast.File, packageName string) (imports fileImportSpecMap) { imports = fileImportSpecMap{"": importSpec{alias: "", name: "", path: packageName}} for _, decl := range file.Decls { - if reflect.ValueOf(decl).Type().String() == "*ast.GenDecl" { - genDecl := decl.(*ast.GenDecl) + if genDecl, ok := decl.(*ast.GenDecl); ok { if genDecl.Tok == token.IMPORT { trace("got an import", genDecl.Specs) for _, spec := range genDecl.Specs { - if "*ast.ImportSpec" == reflect.ValueOf(spec).Type().String() { - spec := spec.(*ast.ImportSpec) + if spec, ok := spec.(*ast.ImportSpec); ok { importPath := spec.Path.Value[1 : len(spec.Path.Value)-1] importName := spec.Name.String() if importName == "" || importName == "" { @@ -138,7 +133,7 @@ func getFileImports(file *ast.File, packageName string) (imports fileImportSpecM name: standardImportName(importPath), path: importPath, } - //trace(" import >>>>>>>>>>>>>>>>>>>>", importName, importPath) + // trace(" import >>>>>>>>>>>>>>>>>>>>", importName, importPath) } } } @@ -191,7 +186,6 @@ func readServicesInPackage(pkg *ast.Package, packageName string, serviceMap map[ if err != nil { return } - } sort.Sort(services) return @@ -201,23 +195,20 @@ func loadConstantTypes(pkg *ast.Package) map[string]interface{} { constantTypes := map[string]interface{}{} for _, file := range pkg.Files { for _, decl := range file.Decls { - if reflect.ValueOf(decl).Type().String() == "*ast.GenDecl" { - genDecl := decl.(*ast.GenDecl) - switch genDecl.Tok { + if genDecl, ok := decl.(*ast.GenDecl); ok { + switch genDecl.Tok { //nolint:exhaustive case token.TYPE: trace("got a type", genDecl.Specs) for _, spec := range genDecl.Specs { - if reflect.ValueOf(spec).Type().String() == "*ast.TypeSpec" { - spec := spec.(*ast.TypeSpec) + if spec, ok := spec.(*ast.TypeSpec); ok { if _, ok := constantTypes[spec.Name.Name]; ok { continue } - switch reflect.ValueOf(spec.Type).Type().String() { - case "*ast.InterfaceType": + switch specType := spec.Type.(type) { + case *ast.InterfaceType: constantTypes[spec.Name.Name] = "any" - case "*ast.Ident": - specIdent := spec.Type.(*ast.Ident) - switch specIdent.Name { + case *ast.Ident: + switch specType.Name { case "byte": constantTypes[spec.Name.Name] = "any" case "string": @@ -239,17 +230,16 @@ func loadConstantTypes(pkg *ast.Package) map[string]interface{} { case token.CONST: trace("got a const", genDecl.Specs) for _, spec := range genDecl.Specs { - if reflect.ValueOf(spec).Type().String() == "*ast.ValueSpec" { - spec := spec.(*ast.ValueSpec) + if spec, ok := spec.(*ast.ValueSpec); ok { if specType, ok := spec.Type.(*ast.Ident); ok { for _, val := range spec.Values { - if reflect.ValueOf(val).Type().String() == "*ast.BasicLit" { + if valType, ok := val.(*ast.BasicLit); ok { if _, ok := constantTypes[specType.Name]; !ok { constantTypes[specType.Name] = map[string]*ast.BasicLit{} } else if _, ok := constantTypes[specType.Name].(map[string]*ast.BasicLit); !ok { constantTypes[specType.Name] = map[string]*ast.BasicLit{} } - constantTypes[specType.Name].(map[string]*ast.BasicLit)[spec.Names[0].Name] = val.(*ast.BasicLit) + constantTypes[specType.Name].(map[string]*ast.BasicLit)[spec.Names[0].Name] = valType //nolint:forcetypeassert } } } @@ -461,7 +451,7 @@ func collectTypes(goPaths []string, gomod config.Namespace, missingTypes map[str fullNameParts := strings.Split(fullName, ".") fullNameParts = fullNameParts[:len(fullNameParts)-1] - //path := fullNameParts[:len(fullNameParts)-1][0] + // path := fullNameParts[:len(fullNameParts)-1][0] packageName := strings.Join(fullNameParts, ".") @@ -514,11 +504,10 @@ func collectTypes(goPaths []string, gomod config.Namespace, missingTypes map[str scalars[packageScalarName] = packageScalar } } - } newNumMissingTypes := len(missingTypeNames()) if newNumMissingTypes > 0 && newNumMissingTypes == lastNumMissing { - //packageStructs, structOK := scannedPackageStructs[packageName] + // packageStructs, structOK := scannedPackageStructs[packageName] for scalarName, scalars := range scannedPackageScalars { fmt.Println("scanned scalars ", scalarName) for _, scalar := range scalars { @@ -597,25 +586,25 @@ func (s *Struct) DepsSatisfied(missingTypes map[string]bool, structs map[string] return false } - //var fieldStructType *StructType = nil - //if field.Value.StructType != nil { - // fieldStructType = field.Value.StructType - //} else if field.Value.Array != nil && field.Value.Array.Value.StructType != nil { - // fieldStructType = field.Value.Array.Value.StructType - //} else if field.Value.Map != nil && field.Value.Map.Value.StructType != nil { - // fieldStructType = field.Value.Map.Value.StructType - //} else if field.Value.Scalar != nil && needsWork(field.Value.Scalar.FullName()) { - // return false - //} else if field.Value.Array != nil && field.Value.Array.Value.Scalar != nil && needsWork(field.Value.Array.Value.Scalar.FullName()) { - // return false - //} else if field.Value.Map != nil && field.Value.Map.Value.Scalar != nil && needsWork(field.Value.Map.Value.Scalar.FullName()) { - // return false - //} - //if fieldStructType != nil { - // if needsWork(fieldStructType.FullName()) { - // return false - // } - //} + // var fieldStructType *StructType = nil + // if field.Value.StructType != nil { + // fieldStructType = field.Value.StructType + // } else if field.Value.Array != nil && field.Value.Array.Value.StructType != nil { + // fieldStructType = field.Value.Array.Value.StructType + // } else if field.Value.Map != nil && field.Value.Map.Value.StructType != nil { + // fieldStructType = field.Value.Map.Value.StructType + // } else if field.Value.Scalar != nil && needsWork(field.Value.Scalar.FullName()) { + // return false + // } else if field.Value.Array != nil && field.Value.Array.Value.Scalar != nil && needsWork(field.Value.Array.Value.Scalar.FullName()) { + // return false + // } else if field.Value.Map != nil && field.Value.Map.Value.Scalar != nil && needsWork(field.Value.Map.Value.Scalar.FullName()) { + // return false + // } + // if fieldStructType != nil { + // if needsWork(fieldStructType.FullName()) { + // return false + // } + // } } return true } @@ -627,7 +616,7 @@ func (s *Struct) DepsSatisfied(missingTypes map[string]bool, structs map[string] return false } //// special handling of union only structs - //if len(s.Fields) == 0 { + // if len(s.Fields) == 0 { // for _, field := range s.UnionFields { // var fieldStructType *StructType = nil // if field.Value.StructType != nil { @@ -704,12 +693,12 @@ func getTypesInPackage( } func getStructTypeForField(value *Value) *StructType { - //field.Value.StructType + // field.Value.StructType var strType *StructType - switch true { + switch { case value.StructType != nil: strType = value.StructType - //case field.Value.ArrayType + // case field.Value.ArrayType case value.Map != nil: strType = getStructTypeForField(value.Map.Value) case value.Array != nil: @@ -719,12 +708,12 @@ func getStructTypeForField(value *Value) *StructType { } func getScalarForField(value *Value) []*Scalar { - //field.Value.StructType + // field.Value.StructType var scalarTypes []*Scalar - switch true { + switch { case value.Scalar != nil: scalarTypes = append(scalarTypes, value.Scalar) - //case field.Value.ArrayType + // case field.Value.ArrayType case value.Map != nil: if value.Map.Key != nil { if v := getScalarForField(value.Map.Key); v != nil { @@ -775,4 +764,4 @@ func collectStructTypes(fields []*Field, structTypes map[string]bool) { } } -//func collectStructs(goPath, structs) +// func collectStructs(goPath, structs) diff --git a/timeext.go b/timeext.go index 3bbf985..7326ae5 100644 --- a/timeext.go +++ b/timeext.go @@ -9,10 +9,11 @@ type TimeExt struct{} var timeExt = &TimeExt{} func (x *TimeExt) ConvertExt(v interface{}) interface{} { - return v.(*time.Time).UnixMilli() + return v.(*time.Time).UnixMilli() //nolint:forcetypeassert } func (x *TimeExt) UpdateExt(dest interface{}, src interface{}) { - tt := dest.(*time.Time) - *tt = time.Unix(0, src.(int64)*int64(time.Millisecond)).Local() + tt := dest.(*time.Time) //nolint:forcetypeassert + + *tt = time.Unix(0, src.(int64)*int64(time.Millisecond)).Local() //nolint:forcetypeassert } diff --git a/transport.go b/transport.go index 419b7c4..4ebd77f 100644 --- a/transport.go +++ b/transport.go @@ -14,7 +14,7 @@ type ClientEncoding int const ( EncodingMsgpack = ClientEncoding(0) - EncodingJson = ClientEncoding(1) + EncodingJson = ClientEncoding(1) //nolint:stylecheck ) var errorType = reflect.TypeOf((*error)(nil)).Elem() @@ -102,11 +102,17 @@ func NewMSGPackDecoderBytes(b []byte) *codec.Decoder { } func SetJSONExt(rt interface{}, tag uint64, ext codec.InterfaceExt) error { - return jsonClientHandle.handle.(*codec.JsonHandle).SetInterfaceExt(reflect.TypeOf(rt), tag, ext) + if value, ok := jsonClientHandle.handle.(*codec.JsonHandle); ok { + return value.SetInterfaceExt(reflect.TypeOf(rt), tag, ext) + } + return errors.New("invalid handle type") } func SetMSGPackExt(rt interface{}, tag uint64, ext codec.BytesExt) error { - return msgpackClientHandle.handle.(*codec.MsgpackHandle).SetBytesExt(reflect.TypeOf(rt), tag, ext) + if value, ok := msgpackClientHandle.handle.(*codec.MsgpackHandle); ok { + return value.SetBytesExt(reflect.TypeOf(rt), tag, ext) + } + return errors.New("invalid handle type") } func getHandleForEncoding(encoding ClientEncoding) *clientHandle { diff --git a/typereader.go b/typereader.go index ff29510..e7b3479 100644 --- a/typereader.go +++ b/typereader.go @@ -136,9 +136,10 @@ func getScalarFromAstIdent(ident *ast.Ident) ScalarType { return ScalarTypeNumber default: if ident.Obj != nil && ident.Obj.Decl != nil && reflect.ValueOf(ident.Obj.Decl).Type().String() == "*ast.TypeSpec" { - typeSpec := ident.Obj.Decl.(*ast.TypeSpec) - if reflect.ValueOf(typeSpec.Type).Type().String() == "*ast.Ident" { - return ScalarType(ident.Name) //getScalarFromAstIdent(typeSpec.Type.(*ast.Ident)) + if typeSpec, ok := ident.Obj.Decl.(*ast.TypeSpec); ok { + if reflect.ValueOf(typeSpec.Type).Type().String() == "*ast.Ident" { + return ScalarType(ident.Name) // getScalarFromAstIdent(typeSpec.Type.(*ast.Ident)) + } } } else if ident.Obj == nil { return ScalarType(ident.Name) @@ -149,7 +150,7 @@ func getScalarFromAstIdent(ident *ast.Ident) ScalarType { func getTypesFromAstType(ident *ast.Ident) (structType string, scalarType ScalarType) { scalarType = getScalarFromAstIdent(ident) - switch scalarType { + switch scalarType { //nolint:gocritic,exhaustive case ScalarTypeNone: structType = ident.Name } @@ -182,8 +183,7 @@ func readAstStarExpr(v *Value, starExpr *ast.StarExpr, fileImports fileImportSpe v.IsPtr = true switch starExprType := starExpr.X.(type) { case *ast.Ident: - ident := starExpr.X.(*ast.Ident) - readAstType(v, ident, fileImports, "") + readAstType(v, starExprType, fileImports, "") case *ast.StructType: // nested anonymous readAstStructType(v, starExprType, fileImports) @@ -212,21 +212,21 @@ func readAstMapType(m *Map, mapType *ast.MapType, fileImports fileImportSpecMap) // todo: implement support for "*ast.Scalar" type (sca) // this is important for scalar types in map keys // Example: - //(*ast.MapType)(0xc420e2cc90)({ - //Map: (token.Pos) 276258, - // Key: (*ast.SelectorExpr)(0xc420301900)({ - // X: (*ast.Ident)(0xc4203018c0)(constants), - // Sel: (*ast.Ident)(0xc4203018e0)(Site) - // }), - //Value: (*ast.ArrayType)(0xc420e2cc60)({ - // Lbrack: (token.Pos) 276277, - // Len: (ast.Expr) , - // Elt: (*ast.SelectorExpr)(0xc420301960)({ - // X: (*ast.Ident)(0xc420301920)(elastic), - // Sel: (*ast.Ident)(0xc420301940)(CategoryDocument) - // }) - // }) - //}) + // (*ast.MapType)(0xc420e2cc90)({ + // Map: (token.Pos) 276258, + // Key: (*ast.SelectorExpr)(0xc420301900)({ + // X: (*ast.Ident)(0xc4203018c0)(constants), + // Sel: (*ast.Ident)(0xc4203018e0)(Site) + // }), + // Value: (*ast.ArrayType)(0xc420e2cc60)({ + // Lbrack: (token.Pos) 276277, + // Len: (ast.Expr) , + // Elt: (*ast.SelectorExpr)(0xc420301960)({ + // X: (*ast.Ident)(0xc420301920)(elastic), + // Sel: (*ast.Ident)(0xc420301940)(CategoryDocument) + // }) + // }) + // }) } // value m.Value.loadExpr(mapType.Value, fileImports) @@ -236,16 +236,16 @@ func readAstSelectorExpr(v *Value, selectorExpr *ast.SelectorExpr, fileImports f switch selExpType := selectorExpr.X.(type) { case *ast.Ident: // that could be the package name - //selectorIdent := selectorExpr.X.(*ast.Ident) + // selectorIdent := selectorExpr.X.(*ast.Ident) // fmt.Println(selectorExpr, selectorExpr.X.(*ast.Ident)) - //readAstType(v, selectorExpr.X.(*ast.Ident), fileImports) + // readAstType(v, selectorExpr.X.(*ast.Ident), fileImports) readAstType(v, selectorExpr.Sel, fileImports, selExpType.Name) if v.StructType != nil { v.StructType.Package = fileImports.getPackagePath(v.StructType.Name) v.StructType.Name = selectorExpr.Sel.Name } - //fmt.Println(selectorExpr.X.(*ast.Ident).Name, ".", selectorExpr.Sel) - //readAstType(v, selectorExpr.Sel, fileImports) + // fmt.Println(selectorExpr.X.(*ast.Ident).Name, ".", selectorExpr.Sel) + // readAstType(v, selectorExpr.Sel, fileImports) default: trace("selectorExpr.Sel !?", selectorExpr.X, reflect.ValueOf(selectorExpr.X).Type().String()) } @@ -261,14 +261,13 @@ func readAstInterfaceType(v *Value, interfaceType *ast.InterfaceType, fileImport } func (v *Value) loadExpr(expr ast.Expr, fileImports fileImportSpecMap) { - switch exprType := expr.(type) { case *ast.ArrayType: v.Array = &Array{Value: &Value{}} switch exprEltType := exprType.Elt.(type) { case *ast.ArrayType: - //readAstArrayType(v.Array.Value, fieldArray.Elt.(*ast.ArrayType), fileImports) + // readAstArrayType(v.Array.Value, fieldArray.Elt.(*ast.ArrayType), fileImports) v.Array.Value.loadExpr(exprEltType, fileImports) case *ast.Ident: readAstType(v.Array.Value, exprEltType, fileImports, "") @@ -369,23 +368,18 @@ func readFieldList(fieldList []*ast.Field, fileImports fileImportSpecMap) (field func extractErrorTypes(file *ast.File, packageName string, errorTypes map[string]bool) (err error) { for _, d := range file.Decls { - if reflect.ValueOf(d).Type().String() == "*ast.FuncDecl" { - funcDecl := d.(*ast.FuncDecl) + if funcDecl, ok := d.(*ast.FuncDecl); ok { if funcDecl.Recv != nil && len(funcDecl.Recv.List) == 1 { firstReceiverField := funcDecl.Recv.List[0] - if "*ast.StarExpr" == reflect.ValueOf(firstReceiverField.Type).Type().String() { - starExpr := firstReceiverField.Type.(*ast.StarExpr) - if "*ast.Ident" == reflect.ValueOf(starExpr.X).Type().String() { - ident := starExpr.X.(*ast.Ident) + if starExpr, ok := firstReceiverField.Type.(*ast.StarExpr); ok { + if ident, ok := starExpr.X.(*ast.Ident); ok { if funcDecl.Name.Name == "Error" && funcDecl.Type.Params.NumFields() == 0 && funcDecl.Type.Results.NumFields() == 1 { returnValueField := funcDecl.Type.Results.List[0] - refl := reflect.ValueOf(returnValueField.Type) - if refl.Type().String() == "*ast.Ident" { - returnValueIdent := returnValueField.Type.(*ast.Ident) + if returnValueIdent, ok := returnValueField.Type.(*ast.Ident); ok { if returnValueIdent.Name == "string" { errorTypes[packageName+"."+ident.Name] = true } - //fmt.Println("error for:", ident.Name, returnValueIdent.Name) + // fmt.Println("error for:", ident.Name, returnValueIdent.Name) } } } @@ -402,39 +396,34 @@ func extractTypes(file *ast.File, packageName string, structs map[string]*Struct if obj.Kind == ast.Typ && obj.Decl != nil { structName := packageName + "." + name - if reflect.ValueOf(obj.Decl).Type().String() == "*ast.TypeSpec" { - typeSpec := obj.Decl.(*ast.TypeSpec) - typeSpecRefl := reflect.ValueOf(typeSpec.Type) - typeName := typeSpecRefl.Type().String() - switch typeName { - case "*ast.StructType": + if typeSpec, ok := obj.Decl.(*ast.TypeSpec); ok { + switch typeSpecType := typeSpec.Type.(type) { + case *ast.StructType: structs[structName] = &Struct{ Name: name, Fields: []*Field{}, Package: packageName, } - structType := typeSpec.Type.(*ast.StructType) trace("StructType", obj.Name) - fields, inlineFields, unionFields := readFieldList(structType.Fields.List, fileImports) + fields, inlineFields, unionFields := readFieldList(typeSpecType.Fields.List, fileImports) structs[structName].Fields = fields structs[structName].InlineFields = inlineFields structs[structName].UnionFields = unionFields - case "*ast.InterfaceType": + case *ast.InterfaceType: trace("Interface", obj.Name) scalars[structName] = &Scalar{ Name: structName, Package: packageName, Type: ScalarTypeAny, } - case "*ast.Ident": + case *ast.Ident: trace("Scalar", obj.Name) - scalarIdent := typeSpec.Type.(*ast.Ident) scalars[structName] = &Scalar{ Name: structName, Package: packageName, - Type: getScalarFromAstIdent(scalarIdent), + Type: getScalarFromAstIdent(typeSpecType), } - case "*ast.ArrayType": + case *ast.ArrayType: arrayValue := &Value{} arrayValue.loadExpr(typeSpec.Type, fileImports) structs[structName] = &Struct{ @@ -442,7 +431,7 @@ func extractTypes(file *ast.File, packageName string, structs map[string]*Struct Package: packageName, Array: arrayValue.Array, } - case "*ast.MapType": + case *ast.MapType: mapValue := &Value{} mapValue.loadExpr(typeSpec.Type, fileImports) structs[structName] = &Struct{ @@ -451,7 +440,7 @@ func extractTypes(file *ast.File, packageName string, structs map[string]*Struct Map: mapValue.Map, } default: - fmt.Println(" ignoring", obj.Name, typeSpecRefl.Type().String()) + fmt.Println(" ignoring", obj.Name, reflect.ValueOf(typeSpec.Type).Type().String()) } } } diff --git a/typescript.go b/typescript.go index 5ba6ee9..69f29d1 100644 --- a/typescript.go +++ b/typescript.go @@ -102,11 +102,10 @@ func (v *Value) tsType(mappings config.TypeScriptMappings, scalars map[string]*S default: ts.app("any") } - return } func tsTypeFromScalarType(scalarType ScalarType) string { - switch scalarType { + switch scalarType { //nolint:exhaustive case ScalarTypeByte: return "string" case ScalarTypeBool: @@ -267,7 +266,6 @@ func renderTypescriptStructsToPackages( packageCodeMap[packageConstantTypeName].l(enum + " = " + packageConstantTypeValuesList[k].Value + ",") } packageCodeMap[packageConstantTypeName].ind(-1).l("}") - } else if packageConstantTypeValuesString, ok := packageConstantTypeValues.(string); ok { packageCodeMap[packageConstantTypeName].l("export type " + packageConstantTypeName + " = " + packageConstantTypeValuesString) } @@ -279,7 +277,6 @@ func renderTypescriptStructsToPackages( if !ok { mappedTypeScript[goPackage] = map[string]*code{} } - return } for _, mapping := range mappings { for structName, structCode := range codeMap[mapping.GoPackage] { @@ -296,9 +293,7 @@ func split(str string, seps []string) []string { for _, sep := range seps { var nextStrs []string for _, str := range strs { - for _, part := range strings.Split(str, sep) { - nextStrs = append(nextStrs, part) - } + nextStrs = append(nextStrs, strings.Split(str, sep)...) } strs = nextStrs res = nextStrs diff --git a/typscriptclient.go b/typscriptclient.go index e768798..78b171f 100644 --- a/typscriptclient.go +++ b/typscriptclient.go @@ -14,8 +14,8 @@ func renderTypescriptClient(service *Service, mappings config.TypeScriptMappings ts.l("export class " + clientName + " {") ts.ind(1) - //ts.l(`static defaultInst = new ` + clientName + `()`) - //ts.l(`constructor(public endpoint = "` + service.Endpoint + `") {}`) + // ts.l(`static defaultInst = new ` + clientName + `()`) + // ts.l(`constructor(public endpoint = "` + service.Endpoint + `") {}`) ts.l(`public static defaultEndpoint = "` + service.Endpoint + `";`) ts.l("constructor(") ts.ind(1)