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]
#- 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]

View File

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

View File

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

View File

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

View File

@ -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()

View File

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

View File

@ -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) {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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)
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 {

View File

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

View File

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

View File

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

View File

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

87
go.go
View File

@ -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)")
@ -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 {`)

View File

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

View File

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

View File

@ -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) {

View File

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

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) 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

View File

@ -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",

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)
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 {
@ -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 == "<nil>" {
@ -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
}
}
}
@ -514,7 +504,6 @@ func collectTypes(goPaths []string, gomod config.Namespace, missingTypes map[str
scalars[packageScalarName] = packageScalar
}
}
}
newNumMissingTypes := len(missingTypeNames())
if newNumMissingTypes > 0 && newNumMissingTypes == lastNumMissing {
@ -706,7 +695,7 @@ func getTypesInPackage(
func getStructTypeForField(value *Value) *StructType {
// field.Value.StructType
var strType *StructType
switch true {
switch {
case value.StructType != nil:
strType = value.StructType
// case field.Value.ArrayType
@ -721,7 +710,7 @@ func getStructTypeForField(value *Value) *StructType {
func getScalarForField(value *Value) []*Scalar {
// field.Value.StructType
var scalarTypes []*Scalar
switch true {
switch {
case value.Scalar != nil:
scalarTypes = append(scalarTypes, value.Scalar)
// case field.Value.ArrayType

View File

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

View File

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

View File

@ -136,10 +136,11 @@ 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 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)
@ -261,7 +261,6 @@ 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{}}
@ -369,19 +368,14 @@ 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
}
@ -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())
}
}
}

View File

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