fix: fix lint errors

This commit is contained in:
Kevin Franklin Kim 2022-08-17 08:48:21 +02:00
parent cf609456fa
commit 5ea922d055
33 changed files with 174 additions and 328 deletions

View File

@ -84,12 +84,12 @@ linters:
#- gochecknoglobals # check that no global variables exist [fast: true, auto-fix: false] #- 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] #- 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] #- 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] - 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] #- 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] #- 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] #- 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] - 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] #- 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] - 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] - 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] - 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] - 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] #- 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] - 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] - 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] - 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] - 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] #- 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] - 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] - 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] - 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] - 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] - structcheck # Finds unused struct fields [fast: false, auto-fix: false]
- stylecheck # Stylecheck is a replacement for golint [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] - 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] - 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] - 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] - 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] - 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] #- 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] - wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]

View File

@ -55,7 +55,7 @@ $(foreach p,$(EXAMPLES),$(eval $(call examples,$(p))))
## Run go mod tidy recursive ## Run go mod tidy recursive
.PHONY: lint .PHONY: lint
lint: lint:
# @golangci-lint run @golangci-lint run
@for name in example/*/; do\ @for name in example/*/; do\
if [ $$name != "example/node_modules/" ]; then \ if [ $$name != "example/node_modules/" ]; then \
echo "-------- $${name} ------------";\ echo "-------- $${name} ------------";\
@ -63,6 +63,16 @@ lint:
fi \ fi \
done 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 ## Run go mod tidy recursive
.PHONY: gomod .PHONY: gomod
gomod: gomod:

View File

@ -4,7 +4,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"go/format" "go/format"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -20,7 +19,7 @@ import (
func deriveCommonJSMapping(conf *config.Config) { func deriveCommonJSMapping(conf *config.Config) {
replacer := strings.NewReplacer(".", "_", "/", "_", "-", "_") replacer := strings.NewReplacer(".", "_", "/", "_", "-", "_")
for _, mapping := range conf.Mappings { 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) deriveCommonJSMapping(conf)
mappedTypeScript := map[string]map[string]*code{} 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) pkgName, services, structs, scalars, constantTypes, err := Read(goPaths, conf.Module, packageName, target.Services, missingTypes, missingConstants)
if err != nil { 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) os.Exit(2)
} }
@ -179,7 +177,7 @@ func Build(conf *config.Config, goPath string) {
) )
// write code into file for debugging // write code into file for debugging
writeErr := ioutil.WriteFile(filename, []byte(code), 0644) writeErr := os.WriteFile(filename, []byte(code), 0644)
if writeErr != nil { if writeErr != nil {
_, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr) _, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr)
os.Exit(5) os.Exit(5)
@ -189,7 +187,7 @@ func Build(conf *config.Config, goPath string) {
os.Exit(5) os.Exit(5)
} }
writeErr := ioutil.WriteFile(filename, codeBytes, 0644) writeErr := os.WriteFile(filename, codeBytes, 0644)
if writeErr != nil { if writeErr != nil {
_, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr) _, _ = fmt.Fprintln(os.Stderr, " could not write go source to file", writeErr)
os.Exit(5) 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) _, _ = fmt.Fprintln(os.Stderr, "building structs for go package", goPackage, "to ts module", mapping.TypeScriptModule, "in file", mapping.Out)
moduleCode := newCode(" ") moduleCode := newCode(" ")
structIndent := -1 structIndent := -3
structIndent = -3
commonJSImports(conf, moduleCode, mapping.Out) commonJSImports(conf, moduleCode, mapping.Out)
@ -251,7 +247,6 @@ func Build(conf *config.Config, goPath string) {
} }
sort.Strings(structNames) sort.Strings(structNames)
for _, structName := range structNames { for _, structName := range structNames {
structCode, ok := mappedStructsMap[structName] structCode, ok := mappedStructsMap[structName]
if ok { if ok {
moduleCode.app(structCode.ind(structIndent).l("").string()) 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) _, _ = fmt.Fprintln(os.Stderr, " failed to update code in", mapping.Out, updateErr)
} }
} }
} }
func updateCode(file string, code string) error { func updateCode(file string, code string) error {
@ -281,10 +275,10 @@ func updateCode(file string, code string) error {
if errMkdirAll != nil { if errMkdirAll != nil {
return errMkdirAll return errMkdirAll
} }
oldCode, _ := ioutil.ReadFile(file) oldCode, _ := os.ReadFile(file)
if string(oldCode) != code { if string(oldCode) != code {
fmt.Println(" writing file", file) 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) fmt.Println(" update file not necessary - unchanged", file)
return nil return nil

View File

@ -4,7 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"fmt" "fmt"
"io/ioutil" "io"
"net/http" "net/http"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -31,7 +31,7 @@ func NewClient() Client {
return &bufferedClient{client: defaultHttpFactory(), handle: getHandleForEncoding(EncodingMsgpack), headers: nil} 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 { if client != nil {
return &bufferedClient{client: client, handle: getHandleForEncoding(EncodingMsgpack), headers: nil} return &bufferedClient{client: client, handle: getHandleForEncoding(EncodingMsgpack), headers: nil}
} else { } else {
@ -43,7 +43,7 @@ func newRequest(ctx context.Context, url string, contentType string, buffer *byt
if buffer == nil { if buffer == nil {
buffer = &bytes.Buffer{} buffer = &bytes.Buffer{}
} }
request, errRequest := http.NewRequestWithContext(ctx, "POST", url, buffer) request, errRequest := http.NewRequestWithContext(ctx, http.MethodPost, url, buffer)
if errRequest != nil { if errRequest != nil {
return nil, errors.Wrap(errRequest, "could not create a request") return nil, errors.Wrap(errRequest, "could not create a request")
} }
@ -71,7 +71,7 @@ func (c *bufferedClient) SetClientEncoding(encoding ClientEncoding) {
c.handle = getHandleForEncoding(encoding) c.handle = getHandleForEncoding(encoding)
} }
func (c *bufferedClient) SetTransportHttpClient(client *http.Client) { func (c *bufferedClient) SetTransportHttpClient(client *http.Client) { //nolint:stylecheck
c.client = client c.client = client
} }
@ -105,7 +105,7 @@ func (c *bufferedClient) Call(ctx context.Context, url string, endpoint string,
// Check status // Check status
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
var msg string 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() msg = "failed to read response body: " + err.Error()
} else { } else {
msg = string(value) msg = string(value)

View File

@ -19,8 +19,8 @@ func usage() {
fmt.Println(os.Args[0], " path/to/build-config.yml") fmt.Println(os.Args[0], " path/to/build-config.yml")
flag.PrintDefaults() flag.PrintDefaults()
} }
func main() {
func main() {
flagDebug := flag.Bool("debug", false, "debug") flagDebug := flag.Bool("debug", false, "debug")
flag.Parse() flag.Parse()

View File

@ -2,7 +2,6 @@ package config
import ( import (
"errors" "errors"
"io/ioutil"
"os" "os"
"path" "path"
"path/filepath" "path/filepath"
@ -65,7 +64,7 @@ type Config struct {
} }
func LoadConfigFile(file string) (conf *Config, err error) { func LoadConfigFile(file string) (conf *Config, err error) {
yamlBytes, readErr := ioutil.ReadFile(file) yamlBytes, readErr := os.ReadFile(file)
if readErr != nil { if readErr != nil {
return nil, errors.New("could not read config file: " + readErr.Error()) 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 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 return nil, err
} else if err == nil { } else if err == nil {
modFile, err := modfile.Parse(path.Join(absPath, "go.mod"), data, nil) modFile, err := modfile.Parse(path.Join(absPath, "go.mod"), data, nil)

View File

@ -66,7 +66,6 @@ func TestLoadConfig(t *testing.T) {
if demoTarget.Services["/service/demo"] != "Service" { if demoTarget.Services["/service/demo"] != "Service" {
t.Fatal("first service is wrong") t.Fatal("first service is wrong")
} }
} }
func TestLoadConfigFile_GomodAbsolute(t *testing.T) { func TestLoadConfigFile_GomodAbsolute(t *testing.T) {

View File

@ -21,12 +21,12 @@ type Error struct {
// NewError returns a new instance // NewError returns a new instance
func NewError(err error) *Error { func NewError(err error) *Error {
// check if already transformed // check if already transformed
if v, ok := err.(*Error); ok { if v, ok := err.(*Error); ok { //nolint:errorlint
return v return v
} }
// skip *withStack error type // skip *withStack error type
if _, ok := err.(interface { if _, ok := err.(interface { //nolint:errorlint
StackTrace() errors.StackTrace StackTrace() errors.StackTrace
}); ok && errors.Unwrap(err) != nil { }); ok && errors.Unwrap(err) != nil {
err = errors.Unwrap(err) err = errors.Unwrap(err)
@ -87,7 +87,7 @@ func (e *Error) Format(s fmt.State, verb rune) {
} }
fallthrough fallthrough
case 's', 'q': case 's', 'q':
io.WriteString(s, e.Error()) _, _ = io.WriteString(s, e.Error())
} }
} }

View File

@ -854,7 +854,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res
retUIntTypeMapTyped_0 := p.service.UIntTypeMapTyped(req.V) retUIntTypeMapTyped_0 := p.service.UIntTypeMapTyped(req.V)
response = ServiceUIntTypeMapTypedResponse{RetUIntTypeMapTyped_0: retUIntTypeMapTyped_0} response = ServiceUIntTypeMapTypedResponse{RetUIntTypeMapTyped_0: retUIntTypeMapTyped_0}
default: default:
fmt.Println("Unkown request type", reflect.TypeOf(request).String()) fmt.Println("Unknown request type", reflect.TypeOf(request).String())
} }
if p.callStatsHandler != nil { if p.callStatsHandler != nil {

View File

@ -4,7 +4,6 @@ package service
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -99,7 +98,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -4,7 +4,6 @@ package backend
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -49,7 +48,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -4,7 +4,6 @@ package frontend
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -44,7 +43,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -77,7 +77,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res
retHello_0 := p.service.Hello(req.V) retHello_0 := p.service.Hello(req.V)
response = ServiceHelloResponse{RetHello_0: retHello_0} response = ServiceHelloResponse{RetHello_0: retHello_0}
default: default:
fmt.Println("Unkown request type", reflect.TypeOf(request).String()) fmt.Println("Unknown request type", reflect.TypeOf(request).String())
} }
if p.callStatsHandler != nil { if p.callStatsHandler != nil {

View File

@ -4,7 +4,6 @@ package service
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -39,7 +38,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -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) 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} response = ServiceVariantHResponse{R1: r1, R2: r2, R3: r3, R4: r4}
default: default:
fmt.Println("Unkown request type", reflect.TypeOf(request).String()) fmt.Println("Unknown request type", reflect.TypeOf(request).String())
} }
if p.callStatsHandler != nil { if p.callStatsHandler != nil {

View File

@ -4,7 +4,6 @@ package service
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -46,7 +45,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -90,7 +90,7 @@ func (p *ServiceGoRPCProxy) handler(clientAddr string, request interface{}) (res
retTimeStruct_0 := p.service.TimeStruct(req.V) retTimeStruct_0 := p.service.TimeStruct(req.V)
response = ServiceTimeStructResponse{RetTimeStruct_0: retTimeStruct_0} response = ServiceTimeStructResponse{RetTimeStruct_0: retTimeStruct_0}
default: default:
fmt.Println("Unkown request type", reflect.TypeOf(request).String()) fmt.Println("Unknown request type", reflect.TypeOf(request).String())
} }
if p.callStatsHandler != nil { if p.callStatsHandler != nil {

View File

@ -4,7 +4,6 @@ package service
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -40,7 +39,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

View File

@ -4,7 +4,6 @@ package service
import ( import (
io "io" io "io"
ioutil "io/ioutil"
http "net/http" http "net/http"
time "time" time "time"
@ -47,7 +46,7 @@ func (p *ServiceGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request)
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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) funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)
callStats, _ := gotsrpc.GetStatsForRequest(r) callStats, _ := gotsrpc.GetStatsForRequest(r)

91
go.go
View File

@ -22,7 +22,7 @@ func (v *Value) goType(aliases map[string]string, packageName string) (t string)
if v.IsPtr { if v.IsPtr {
t = "*" t = "*"
} }
switch true { switch {
case v.Array != nil: case v.Array != nil:
t += "[]" + v.Array.Value.goType(aliases, packageName) t += "[]" + v.Array.Value.goType(aliases, packageName)
case len(v.GoScalarType) > 0: case len(v.GoScalarType) > 0:
@ -49,80 +49,6 @@ func (v *Value) goType(aliases map[string]string, packageName string) (t string)
return 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 { func lcfirst(str string) string {
return strfirst(str, strings.ToLower) return strfirst(str, strings.ToLower)
} }
@ -139,7 +65,6 @@ func strfirst(str string, strfunc func(string) string) string {
} else { } else {
res += string(char) res += string(char)
} }
} }
return res 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) { func extractImport(packageName string, fullPackageName string, aliases map[string]string) {
r := strings.NewReplacer(".", "_", "/", "_", "-", "_") r := strings.NewReplacer(".", "_", "/", "_", "-", "_")
if packageName != fullPackageName { if packageName != fullPackageName {
alias, ok := aliases[packageName] if _, ok := aliases[packageName]; !ok {
if !ok {
packageParts := strings.Split(packageName, "/") packageParts := strings.Split(packageName, "/")
beautifulAlias := packageParts[len(packageParts)-1] beautifulAlias := packageParts[len(packageParts)-1]
uglyAlias := r.Replace(packageName) uglyAlias := r.Replace(packageName)
alias = uglyAlias //beautifulAlias alias := uglyAlias // beautifulAlias
for _, otherAlias := range aliases { for _, otherAlias := range aliases {
if otherAlias == beautifulAlias { if otherAlias == beautifulAlias {
alias = uglyAlias alias = uglyAlias
@ -189,7 +113,6 @@ func renderTSRPCServiceProxies(services ServiceList, fullPackageName string, pac
"time": "time", "time": "time",
"net/http": "http", "net/http": "http",
"io": "io", "io": "io",
"io/ioutil": "ioutil",
"github.com/foomo/gotsrpc/v2": "gotsrpc", "github.com/foomo/gotsrpc/v2": "gotsrpc",
} }
for _, service := range services { for _, service := range services {
@ -256,7 +179,7 @@ func renderTSRPCServiceProxies(services ServiceList, fullPackageName string, pac
gotsrpc.ErrorMethodNotAllowed(w) gotsrpc.ErrorMethodNotAllowed(w)
return 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)") g.l("funcName := gotsrpc.GetCalledFunc(r, p.EndPoint)")
@ -435,7 +358,7 @@ func renderTSRPCServiceClients(services ServiceList, fullPackageName string, pac
interfaceName := service.Name + "GoTSRPCClient" interfaceName := service.Name + "GoTSRPCClient"
clientName := "HTTP" + interfaceName clientName := "HTTP" + interfaceName
//Render Interface // Render Interface
g.l(`type ` + interfaceName + ` interface { `) g.l(`type ` + interfaceName + ` interface { `)
for _, method := range service.Methods { for _, method := range service.Methods {
ms := newMethodSignature(method, aliases, fullPackageName) ms := newMethodSignature(method, aliases, fullPackageName)
@ -444,7 +367,7 @@ func renderTSRPCServiceClients(services ServiceList, fullPackageName string, pac
g.l(`} `) g.l(`} `)
//Render Constructors // Render Constructors
g.l(` g.l(`
type ` + clientName + ` struct { type ` + clientName + ` struct {
URL string 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(`response = ` + service.Name + method.Name + `Response{` + strings.Join(retParams, ", ") + `}`)
} }
g.l(`default:`) 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.l(`}`)
g.nl() g.nl()
g.l(`if p.callStatsHandler != nil {`) g.l(`if p.callStatsHandler != nil {`)

View File

@ -21,7 +21,9 @@ import (
"github.com/foomo/gotsrpc/v2/config" "github.com/foomo/gotsrpc/v2/config"
) )
const contextStatsKey = "gotsrpcStats" type contextKey string
const contextStatsKey contextKey = "gotsrpcStats"
func GetCalledFunc(r *http.Request, endPoint string) string { func GetCalledFunc(r *http.Request, endPoint string) string {
return strings.TrimPrefix(r.URL.Path, endPoint+"/") 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) { func GetStatsForRequest(r *http.Request) (*CallStats, bool) {
if value := r.Context().Value(contextStatsKey); value != nil { if value, ok := r.Context().Value(contextStatsKey).(*CallStats); ok && value != nil {
return value.(*CallStats), true return value, true
} else { } else {
return &CallStats{}, false return &CallStats{}, false
} }
@ -197,9 +199,7 @@ func parsePackage(goPaths []string, gomod config.Namespace, packageName string)
} }
var foundPackages []string var foundPackages []string
sortedGoPaths := make([]string, len(goPaths)) sortedGoPaths := make([]string, len(goPaths))
for iGoPath := range goPaths { copy(sortedGoPaths, goPaths)
sortedGoPaths[iGoPath] = goPaths[iGoPath]
}
sort.Sort(byLen(sortedGoPaths)) sort.Sort(byLen(sortedGoPaths))
var parsedPkg *ast.Package var parsedPkg *ast.Package

View File

@ -9,7 +9,7 @@ import (
// Default Client Factory // Default Client Factory
// https://medium.com/@nate510/don-t-use-go-s-default-http-client-4804cb19f779 // 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{ transport := &http.Transport{
Proxy: http.ProxyFromEnvironment, Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{ 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 defaultHttpFactory = factory
} }

View File

@ -1,9 +1,10 @@
package gotsrpc package gotsrpc
import ( import (
"github.com/stretchr/testify/assert"
"net/http" "net/http"
"testing" "testing"
"github.com/stretchr/testify/assert"
) )
func TestSetDefaultHttpClientFactory(t *testing.T) { func TestSetDefaultHttpClientFactory(t *testing.T) {

View File

@ -10,12 +10,11 @@ import (
func TestInstrumentedService(t *testing.T) { func TestInstrumentedService(t *testing.T) {
middleware := func(w http.ResponseWriter, r *http.Request) { 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.Func = "func"
s.Package = "package" s.Package = "package"
s.Service = "service" s.Service = "service"
} }
return
} }
t.Run("stats", func(t *testing.T) { t.Run("stats", func(t *testing.T) {
@ -29,7 +28,7 @@ func TestInstrumentedService(t *testing.T) {
}) })
rsp := httptest.NewRecorder() rsp := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/test", nil) req := httptest.NewRequest(http.MethodGet, "/test", nil)
handler(rsp, req) handler(rsp, req)

View File

@ -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) 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) 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 { type Method struct {
Name string Name string
Args []*Field Args []*Field

View File

@ -3,12 +3,13 @@ package prometheus
import ( import (
"net/http" "net/http"
"github.com/foomo/gotsrpc/v2"
p "github.com/prometheus/client_golang/prometheus" p "github.com/prometheus/client_golang/prometheus"
"github.com/foomo/gotsrpc/v2"
) )
func InstrumentService(s http.HandlerFunc) (handler http.HandlerFunc) { func InstrumentService(s http.HandlerFunc) (handler http.HandlerFunc) {
requestDuration := p.NewSummaryVec(p.SummaryOpts{ requestDuration := p.NewSummaryVec(p.SummaryOpts{ //nolint:promlinter
Namespace: "gotsrpc", Namespace: "gotsrpc",
Subsystem: "service", Subsystem: "service",
Name: "time_nanoseconds", Name: "time_nanoseconds",

View File

@ -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
}

View File

@ -34,11 +34,8 @@ func readServiceFile(file *ast.File, packageName string, services ServiceList) e
trace("that is a method named", funcDecl.Name) trace("that is a method named", funcDecl.Name)
if len(funcDecl.Recv.List) == 1 { if len(funcDecl.Recv.List) == 1 {
firstReceiverField := funcDecl.Recv.List[0] firstReceiverField := funcDecl.Recv.List[0]
if "*ast.StarExpr" == reflect.ValueOf(firstReceiverField.Type).Type().String() { if starExpr, ok := firstReceiverField.Type.(*ast.StarExpr); ok {
starExpr := firstReceiverField.Type.(*ast.StarExpr) if ident, ok := starExpr.X.(*ast.Ident); ok {
if "*ast.Ident" == reflect.ValueOf(starExpr.X).Type().String() {
ident := starExpr.X.(*ast.Ident)
service, ok := findService(ident.Name) service, ok := findService(ident.Name)
firstCharOfMethodName := funcDecl.Name.Name[0:1] firstCharOfMethodName := funcDecl.Name.Name[0:1]
if !ok || strings.ToLower(firstCharOfMethodName) == firstCharOfMethodName { if !ok || strings.ToLower(firstCharOfMethodName) == firstCharOfMethodName {
@ -77,7 +74,7 @@ func readServiceFile(file *ast.File, packageName string, services ServiceList) e
} }
mname := fieldDecl.Names[0] mname := fieldDecl.Names[0]
trace(" on sth:", mname.Name) 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{ service.Methods = append(service.Methods, &Method{
Name: mname.Name, Name: mname.Name,
Args: readFields(funcDecl.Params, fileImports), Args: readFields(funcDecl.Params, fileImports),
@ -121,13 +118,11 @@ func standardImportName(importPath string) string {
func getFileImports(file *ast.File, packageName string) (imports fileImportSpecMap) { func getFileImports(file *ast.File, packageName string) (imports fileImportSpecMap) {
imports = fileImportSpecMap{"": importSpec{alias: "", name: "", path: packageName}} imports = fileImportSpecMap{"": importSpec{alias: "", name: "", path: packageName}}
for _, decl := range file.Decls { for _, decl := range file.Decls {
if reflect.ValueOf(decl).Type().String() == "*ast.GenDecl" { if genDecl, ok := decl.(*ast.GenDecl); ok {
genDecl := decl.(*ast.GenDecl)
if genDecl.Tok == token.IMPORT { if genDecl.Tok == token.IMPORT {
trace("got an import", genDecl.Specs) trace("got an import", genDecl.Specs)
for _, spec := range genDecl.Specs { for _, spec := range genDecl.Specs {
if "*ast.ImportSpec" == reflect.ValueOf(spec).Type().String() { if spec, ok := spec.(*ast.ImportSpec); ok {
spec := spec.(*ast.ImportSpec)
importPath := spec.Path.Value[1 : len(spec.Path.Value)-1] importPath := spec.Path.Value[1 : len(spec.Path.Value)-1]
importName := spec.Name.String() importName := spec.Name.String()
if importName == "" || importName == "<nil>" { if importName == "" || importName == "<nil>" {
@ -138,7 +133,7 @@ func getFileImports(file *ast.File, packageName string) (imports fileImportSpecM
name: standardImportName(importPath), name: standardImportName(importPath),
path: 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 { if err != nil {
return return
} }
} }
sort.Sort(services) sort.Sort(services)
return return
@ -201,23 +195,20 @@ func loadConstantTypes(pkg *ast.Package) map[string]interface{} {
constantTypes := map[string]interface{}{} constantTypes := map[string]interface{}{}
for _, file := range pkg.Files { for _, file := range pkg.Files {
for _, decl := range file.Decls { for _, decl := range file.Decls {
if reflect.ValueOf(decl).Type().String() == "*ast.GenDecl" { if genDecl, ok := decl.(*ast.GenDecl); ok {
genDecl := decl.(*ast.GenDecl) switch genDecl.Tok { //nolint:exhaustive
switch genDecl.Tok {
case token.TYPE: case token.TYPE:
trace("got a type", genDecl.Specs) trace("got a type", genDecl.Specs)
for _, spec := range genDecl.Specs { for _, spec := range genDecl.Specs {
if reflect.ValueOf(spec).Type().String() == "*ast.TypeSpec" { if spec, ok := spec.(*ast.TypeSpec); ok {
spec := spec.(*ast.TypeSpec)
if _, ok := constantTypes[spec.Name.Name]; ok { if _, ok := constantTypes[spec.Name.Name]; ok {
continue continue
} }
switch reflect.ValueOf(spec.Type).Type().String() { switch specType := spec.Type.(type) {
case "*ast.InterfaceType": case *ast.InterfaceType:
constantTypes[spec.Name.Name] = "any" constantTypes[spec.Name.Name] = "any"
case "*ast.Ident": case *ast.Ident:
specIdent := spec.Type.(*ast.Ident) switch specType.Name {
switch specIdent.Name {
case "byte": case "byte":
constantTypes[spec.Name.Name] = "any" constantTypes[spec.Name.Name] = "any"
case "string": case "string":
@ -239,17 +230,16 @@ func loadConstantTypes(pkg *ast.Package) map[string]interface{} {
case token.CONST: case token.CONST:
trace("got a const", genDecl.Specs) trace("got a const", genDecl.Specs)
for _, spec := range genDecl.Specs { for _, spec := range genDecl.Specs {
if reflect.ValueOf(spec).Type().String() == "*ast.ValueSpec" { if spec, ok := spec.(*ast.ValueSpec); ok {
spec := spec.(*ast.ValueSpec)
if specType, ok := spec.Type.(*ast.Ident); ok { if specType, ok := spec.Type.(*ast.Ident); ok {
for _, val := range spec.Values { 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 { if _, ok := constantTypes[specType.Name]; !ok {
constantTypes[specType.Name] = map[string]*ast.BasicLit{} constantTypes[specType.Name] = map[string]*ast.BasicLit{}
} else if _, ok := constantTypes[specType.Name].(map[string]*ast.BasicLit); !ok { } 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{}
} }
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 := strings.Split(fullName, ".")
fullNameParts = fullNameParts[:len(fullNameParts)-1] fullNameParts = fullNameParts[:len(fullNameParts)-1]
//path := fullNameParts[:len(fullNameParts)-1][0] // path := fullNameParts[:len(fullNameParts)-1][0]
packageName := strings.Join(fullNameParts, ".") packageName := strings.Join(fullNameParts, ".")
@ -514,11 +504,10 @@ func collectTypes(goPaths []string, gomod config.Namespace, missingTypes map[str
scalars[packageScalarName] = packageScalar scalars[packageScalarName] = packageScalar
} }
} }
} }
newNumMissingTypes := len(missingTypeNames()) newNumMissingTypes := len(missingTypeNames())
if newNumMissingTypes > 0 && newNumMissingTypes == lastNumMissing { if newNumMissingTypes > 0 && newNumMissingTypes == lastNumMissing {
//packageStructs, structOK := scannedPackageStructs[packageName] // packageStructs, structOK := scannedPackageStructs[packageName]
for scalarName, scalars := range scannedPackageScalars { for scalarName, scalars := range scannedPackageScalars {
fmt.Println("scanned scalars ", scalarName) fmt.Println("scanned scalars ", scalarName)
for _, scalar := range scalars { for _, scalar := range scalars {
@ -597,25 +586,25 @@ func (s *Struct) DepsSatisfied(missingTypes map[string]bool, structs map[string]
return false return false
} }
//var fieldStructType *StructType = nil // var fieldStructType *StructType = nil
//if field.Value.StructType != nil { // if field.Value.StructType != nil {
// fieldStructType = field.Value.StructType // fieldStructType = field.Value.StructType
//} else if field.Value.Array != nil && field.Value.Array.Value.StructType != nil { // } else if field.Value.Array != nil && field.Value.Array.Value.StructType != nil {
// fieldStructType = field.Value.Array.Value.StructType // fieldStructType = field.Value.Array.Value.StructType
//} else if field.Value.Map != nil && field.Value.Map.Value.StructType != nil { // } else if field.Value.Map != nil && field.Value.Map.Value.StructType != nil {
// fieldStructType = field.Value.Map.Value.StructType // fieldStructType = field.Value.Map.Value.StructType
//} else if field.Value.Scalar != nil && needsWork(field.Value.Scalar.FullName()) { // } else if field.Value.Scalar != nil && needsWork(field.Value.Scalar.FullName()) {
// return false // return false
//} else if field.Value.Array != nil && field.Value.Array.Value.Scalar != nil && needsWork(field.Value.Array.Value.Scalar.FullName()) { // } else if field.Value.Array != nil && field.Value.Array.Value.Scalar != nil && needsWork(field.Value.Array.Value.Scalar.FullName()) {
// return false // return false
//} else if field.Value.Map != nil && field.Value.Map.Value.Scalar != nil && needsWork(field.Value.Map.Value.Scalar.FullName()) { // } else if field.Value.Map != nil && field.Value.Map.Value.Scalar != nil && needsWork(field.Value.Map.Value.Scalar.FullName()) {
// return false // return false
//} // }
//if fieldStructType != nil { // if fieldStructType != nil {
// if needsWork(fieldStructType.FullName()) { // if needsWork(fieldStructType.FullName()) {
// return false // return false
// } // }
//} // }
} }
return true return true
} }
@ -627,7 +616,7 @@ func (s *Struct) DepsSatisfied(missingTypes map[string]bool, structs map[string]
return false return false
} }
//// special handling of union only structs //// special handling of union only structs
//if len(s.Fields) == 0 { // if len(s.Fields) == 0 {
// for _, field := range s.UnionFields { // for _, field := range s.UnionFields {
// var fieldStructType *StructType = nil // var fieldStructType *StructType = nil
// if field.Value.StructType != nil { // if field.Value.StructType != nil {
@ -704,12 +693,12 @@ func getTypesInPackage(
} }
func getStructTypeForField(value *Value) *StructType { func getStructTypeForField(value *Value) *StructType {
//field.Value.StructType // field.Value.StructType
var strType *StructType var strType *StructType
switch true { switch {
case value.StructType != nil: case value.StructType != nil:
strType = value.StructType strType = value.StructType
//case field.Value.ArrayType // case field.Value.ArrayType
case value.Map != nil: case value.Map != nil:
strType = getStructTypeForField(value.Map.Value) strType = getStructTypeForField(value.Map.Value)
case value.Array != nil: case value.Array != nil:
@ -719,12 +708,12 @@ func getStructTypeForField(value *Value) *StructType {
} }
func getScalarForField(value *Value) []*Scalar { func getScalarForField(value *Value) []*Scalar {
//field.Value.StructType // field.Value.StructType
var scalarTypes []*Scalar var scalarTypes []*Scalar
switch true { switch {
case value.Scalar != nil: case value.Scalar != nil:
scalarTypes = append(scalarTypes, value.Scalar) scalarTypes = append(scalarTypes, value.Scalar)
//case field.Value.ArrayType // case field.Value.ArrayType
case value.Map != nil: case value.Map != nil:
if value.Map.Key != nil { if value.Map.Key != nil {
if v := getScalarForField(value.Map.Key); v != 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)

View File

@ -9,10 +9,11 @@ type TimeExt struct{}
var timeExt = &TimeExt{} var timeExt = &TimeExt{}
func (x *TimeExt) ConvertExt(v interface{}) interface{} { 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{}) { func (x *TimeExt) UpdateExt(dest interface{}, src interface{}) {
tt := dest.(*time.Time) tt := dest.(*time.Time) //nolint:forcetypeassert
*tt = time.Unix(0, src.(int64)*int64(time.Millisecond)).Local()
*tt = time.Unix(0, src.(int64)*int64(time.Millisecond)).Local() //nolint:forcetypeassert
} }

View File

@ -14,7 +14,7 @@ type ClientEncoding int
const ( const (
EncodingMsgpack = ClientEncoding(0) EncodingMsgpack = ClientEncoding(0)
EncodingJson = ClientEncoding(1) EncodingJson = ClientEncoding(1) //nolint:stylecheck
) )
var errorType = reflect.TypeOf((*error)(nil)).Elem() 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 { 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 { 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 { func getHandleForEncoding(encoding ClientEncoding) *clientHandle {

View File

@ -136,9 +136,10 @@ func getScalarFromAstIdent(ident *ast.Ident) ScalarType {
return ScalarTypeNumber return ScalarTypeNumber
default: default:
if ident.Obj != nil && ident.Obj.Decl != nil && reflect.ValueOf(ident.Obj.Decl).Type().String() == "*ast.TypeSpec" { if ident.Obj != nil && ident.Obj.Decl != nil && reflect.ValueOf(ident.Obj.Decl).Type().String() == "*ast.TypeSpec" {
typeSpec := ident.Obj.Decl.(*ast.TypeSpec) if typeSpec, ok := ident.Obj.Decl.(*ast.TypeSpec); ok {
if reflect.ValueOf(typeSpec.Type).Type().String() == "*ast.Ident" { if reflect.ValueOf(typeSpec.Type).Type().String() == "*ast.Ident" {
return ScalarType(ident.Name) //getScalarFromAstIdent(typeSpec.Type.(*ast.Ident)) return ScalarType(ident.Name) // getScalarFromAstIdent(typeSpec.Type.(*ast.Ident))
}
} }
} else if ident.Obj == nil { } else if ident.Obj == nil {
return ScalarType(ident.Name) return ScalarType(ident.Name)
@ -149,7 +150,7 @@ func getScalarFromAstIdent(ident *ast.Ident) ScalarType {
func getTypesFromAstType(ident *ast.Ident) (structType string, scalarType ScalarType) { func getTypesFromAstType(ident *ast.Ident) (structType string, scalarType ScalarType) {
scalarType = getScalarFromAstIdent(ident) scalarType = getScalarFromAstIdent(ident)
switch scalarType { switch scalarType { //nolint:gocritic,exhaustive
case ScalarTypeNone: case ScalarTypeNone:
structType = ident.Name structType = ident.Name
} }
@ -182,8 +183,7 @@ func readAstStarExpr(v *Value, starExpr *ast.StarExpr, fileImports fileImportSpe
v.IsPtr = true v.IsPtr = true
switch starExprType := starExpr.X.(type) { switch starExprType := starExpr.X.(type) {
case *ast.Ident: case *ast.Ident:
ident := starExpr.X.(*ast.Ident) readAstType(v, starExprType, fileImports, "")
readAstType(v, ident, fileImports, "")
case *ast.StructType: case *ast.StructType:
// nested anonymous // nested anonymous
readAstStructType(v, starExprType, fileImports) 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) // todo: implement support for "*ast.Scalar" type (sca)
// this is important for scalar types in map keys // this is important for scalar types in map keys
// Example: // Example:
//(*ast.MapType)(0xc420e2cc90)({ // (*ast.MapType)(0xc420e2cc90)({
//Map: (token.Pos) 276258, // Map: (token.Pos) 276258,
// Key: (*ast.SelectorExpr)(0xc420301900)({ // Key: (*ast.SelectorExpr)(0xc420301900)({
// X: (*ast.Ident)(0xc4203018c0)(constants), // X: (*ast.Ident)(0xc4203018c0)(constants),
// Sel: (*ast.Ident)(0xc4203018e0)(Site) // Sel: (*ast.Ident)(0xc4203018e0)(Site)
// }), // }),
//Value: (*ast.ArrayType)(0xc420e2cc60)({ // Value: (*ast.ArrayType)(0xc420e2cc60)({
// Lbrack: (token.Pos) 276277, // Lbrack: (token.Pos) 276277,
// Len: (ast.Expr) <nil>, // Len: (ast.Expr) <nil>,
// Elt: (*ast.SelectorExpr)(0xc420301960)({ // Elt: (*ast.SelectorExpr)(0xc420301960)({
// X: (*ast.Ident)(0xc420301920)(elastic), // X: (*ast.Ident)(0xc420301920)(elastic),
// Sel: (*ast.Ident)(0xc420301940)(CategoryDocument) // Sel: (*ast.Ident)(0xc420301940)(CategoryDocument)
// }) // })
// }) // })
//}) // })
} }
// value // value
m.Value.loadExpr(mapType.Value, fileImports) m.Value.loadExpr(mapType.Value, fileImports)
@ -236,16 +236,16 @@ func readAstSelectorExpr(v *Value, selectorExpr *ast.SelectorExpr, fileImports f
switch selExpType := selectorExpr.X.(type) { switch selExpType := selectorExpr.X.(type) {
case *ast.Ident: case *ast.Ident:
// that could be the package name // that could be the package name
//selectorIdent := selectorExpr.X.(*ast.Ident) // selectorIdent := selectorExpr.X.(*ast.Ident)
// fmt.Println(selectorExpr, 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) readAstType(v, selectorExpr.Sel, fileImports, selExpType.Name)
if v.StructType != nil { if v.StructType != nil {
v.StructType.Package = fileImports.getPackagePath(v.StructType.Name) v.StructType.Package = fileImports.getPackagePath(v.StructType.Name)
v.StructType.Name = selectorExpr.Sel.Name v.StructType.Name = selectorExpr.Sel.Name
} }
//fmt.Println(selectorExpr.X.(*ast.Ident).Name, ".", selectorExpr.Sel) // fmt.Println(selectorExpr.X.(*ast.Ident).Name, ".", selectorExpr.Sel)
//readAstType(v, selectorExpr.Sel, fileImports) // readAstType(v, selectorExpr.Sel, fileImports)
default: default:
trace("selectorExpr.Sel !?", selectorExpr.X, reflect.ValueOf(selectorExpr.X).Type().String()) 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) { func (v *Value) loadExpr(expr ast.Expr, fileImports fileImportSpecMap) {
switch exprType := expr.(type) { switch exprType := expr.(type) {
case *ast.ArrayType: case *ast.ArrayType:
v.Array = &Array{Value: &Value{}} v.Array = &Array{Value: &Value{}}
switch exprEltType := exprType.Elt.(type) { switch exprEltType := exprType.Elt.(type) {
case *ast.ArrayType: 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) v.Array.Value.loadExpr(exprEltType, fileImports)
case *ast.Ident: case *ast.Ident:
readAstType(v.Array.Value, exprEltType, fileImports, "") 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) { func extractErrorTypes(file *ast.File, packageName string, errorTypes map[string]bool) (err error) {
for _, d := range file.Decls { for _, d := range file.Decls {
if reflect.ValueOf(d).Type().String() == "*ast.FuncDecl" { if funcDecl, ok := d.(*ast.FuncDecl); ok {
funcDecl := d.(*ast.FuncDecl)
if funcDecl.Recv != nil && len(funcDecl.Recv.List) == 1 { if funcDecl.Recv != nil && len(funcDecl.Recv.List) == 1 {
firstReceiverField := funcDecl.Recv.List[0] firstReceiverField := funcDecl.Recv.List[0]
if "*ast.StarExpr" == reflect.ValueOf(firstReceiverField.Type).Type().String() { if starExpr, ok := firstReceiverField.Type.(*ast.StarExpr); ok {
starExpr := firstReceiverField.Type.(*ast.StarExpr) if ident, ok := starExpr.X.(*ast.Ident); ok {
if "*ast.Ident" == reflect.ValueOf(starExpr.X).Type().String() {
ident := starExpr.X.(*ast.Ident)
if funcDecl.Name.Name == "Error" && funcDecl.Type.Params.NumFields() == 0 && funcDecl.Type.Results.NumFields() == 1 { if funcDecl.Name.Name == "Error" && funcDecl.Type.Params.NumFields() == 0 && funcDecl.Type.Results.NumFields() == 1 {
returnValueField := funcDecl.Type.Results.List[0] returnValueField := funcDecl.Type.Results.List[0]
refl := reflect.ValueOf(returnValueField.Type) if returnValueIdent, ok := returnValueField.Type.(*ast.Ident); ok {
if refl.Type().String() == "*ast.Ident" {
returnValueIdent := returnValueField.Type.(*ast.Ident)
if returnValueIdent.Name == "string" { if returnValueIdent.Name == "string" {
errorTypes[packageName+"."+ident.Name] = true 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 { if obj.Kind == ast.Typ && obj.Decl != nil {
structName := packageName + "." + name structName := packageName + "." + name
if reflect.ValueOf(obj.Decl).Type().String() == "*ast.TypeSpec" { if typeSpec, ok := obj.Decl.(*ast.TypeSpec); ok {
typeSpec := obj.Decl.(*ast.TypeSpec) switch typeSpecType := typeSpec.Type.(type) {
typeSpecRefl := reflect.ValueOf(typeSpec.Type) case *ast.StructType:
typeName := typeSpecRefl.Type().String()
switch typeName {
case "*ast.StructType":
structs[structName] = &Struct{ structs[structName] = &Struct{
Name: name, Name: name,
Fields: []*Field{}, Fields: []*Field{},
Package: packageName, Package: packageName,
} }
structType := typeSpec.Type.(*ast.StructType)
trace("StructType", obj.Name) 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].Fields = fields
structs[structName].InlineFields = inlineFields structs[structName].InlineFields = inlineFields
structs[structName].UnionFields = unionFields structs[structName].UnionFields = unionFields
case "*ast.InterfaceType": case *ast.InterfaceType:
trace("Interface", obj.Name) trace("Interface", obj.Name)
scalars[structName] = &Scalar{ scalars[structName] = &Scalar{
Name: structName, Name: structName,
Package: packageName, Package: packageName,
Type: ScalarTypeAny, Type: ScalarTypeAny,
} }
case "*ast.Ident": case *ast.Ident:
trace("Scalar", obj.Name) trace("Scalar", obj.Name)
scalarIdent := typeSpec.Type.(*ast.Ident)
scalars[structName] = &Scalar{ scalars[structName] = &Scalar{
Name: structName, Name: structName,
Package: packageName, Package: packageName,
Type: getScalarFromAstIdent(scalarIdent), Type: getScalarFromAstIdent(typeSpecType),
} }
case "*ast.ArrayType": case *ast.ArrayType:
arrayValue := &Value{} arrayValue := &Value{}
arrayValue.loadExpr(typeSpec.Type, fileImports) arrayValue.loadExpr(typeSpec.Type, fileImports)
structs[structName] = &Struct{ structs[structName] = &Struct{
@ -442,7 +431,7 @@ func extractTypes(file *ast.File, packageName string, structs map[string]*Struct
Package: packageName, Package: packageName,
Array: arrayValue.Array, Array: arrayValue.Array,
} }
case "*ast.MapType": case *ast.MapType:
mapValue := &Value{} mapValue := &Value{}
mapValue.loadExpr(typeSpec.Type, fileImports) mapValue.loadExpr(typeSpec.Type, fileImports)
structs[structName] = &Struct{ structs[structName] = &Struct{
@ -451,7 +440,7 @@ func extractTypes(file *ast.File, packageName string, structs map[string]*Struct
Map: mapValue.Map, Map: mapValue.Map,
} }
default: default:
fmt.Println(" ignoring", obj.Name, typeSpecRefl.Type().String()) fmt.Println(" ignoring", obj.Name, reflect.ValueOf(typeSpec.Type).Type().String())
} }
} }
} }

View File

@ -102,11 +102,10 @@ func (v *Value) tsType(mappings config.TypeScriptMappings, scalars map[string]*S
default: default:
ts.app("any") ts.app("any")
} }
return
} }
func tsTypeFromScalarType(scalarType ScalarType) string { func tsTypeFromScalarType(scalarType ScalarType) string {
switch scalarType { switch scalarType { //nolint:exhaustive
case ScalarTypeByte: case ScalarTypeByte:
return "string" return "string"
case ScalarTypeBool: case ScalarTypeBool:
@ -267,7 +266,6 @@ func renderTypescriptStructsToPackages(
packageCodeMap[packageConstantTypeName].l(enum + " = " + packageConstantTypeValuesList[k].Value + ",") packageCodeMap[packageConstantTypeName].l(enum + " = " + packageConstantTypeValuesList[k].Value + ",")
} }
packageCodeMap[packageConstantTypeName].ind(-1).l("}") packageCodeMap[packageConstantTypeName].ind(-1).l("}")
} else if packageConstantTypeValuesString, ok := packageConstantTypeValues.(string); ok { } else if packageConstantTypeValuesString, ok := packageConstantTypeValues.(string); ok {
packageCodeMap[packageConstantTypeName].l("export type " + packageConstantTypeName + " = " + packageConstantTypeValuesString) packageCodeMap[packageConstantTypeName].l("export type " + packageConstantTypeName + " = " + packageConstantTypeValuesString)
} }
@ -279,7 +277,6 @@ func renderTypescriptStructsToPackages(
if !ok { if !ok {
mappedTypeScript[goPackage] = map[string]*code{} mappedTypeScript[goPackage] = map[string]*code{}
} }
return
} }
for _, mapping := range mappings { for _, mapping := range mappings {
for structName, structCode := range codeMap[mapping.GoPackage] { for structName, structCode := range codeMap[mapping.GoPackage] {
@ -296,9 +293,7 @@ func split(str string, seps []string) []string {
for _, sep := range seps { for _, sep := range seps {
var nextStrs []string var nextStrs []string
for _, str := range strs { for _, str := range strs {
for _, part := range strings.Split(str, sep) { nextStrs = append(nextStrs, strings.Split(str, sep)...)
nextStrs = append(nextStrs, part)
}
} }
strs = nextStrs strs = nextStrs
res = nextStrs res = nextStrs

View File

@ -14,8 +14,8 @@ func renderTypescriptClient(service *Service, mappings config.TypeScriptMappings
ts.l("export class " + clientName + " {") ts.l("export class " + clientName + " {")
ts.ind(1) ts.ind(1)
//ts.l(`static defaultInst = new ` + clientName + `()`) // ts.l(`static defaultInst = new ` + clientName + `()`)
//ts.l(`constructor(public endpoint = "` + service.Endpoint + `") {}`) // ts.l(`constructor(public endpoint = "` + service.Endpoint + `") {}`)
ts.l(`public static defaultEndpoint = "` + service.Endpoint + `";`) ts.l(`public static defaultEndpoint = "` + service.Endpoint + `";`)
ts.l("constructor(") ts.l("constructor(")
ts.ind(1) ts.ind(1)