Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: fix linter #289 #315

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,6 @@ linters:
issues:
new: false
fix: false
new-from-rev: 2399c75fbd6c738c4cddf38a3ad7f5f97367e5ec
exclude-rules:
- path: _test\.go
linters:
Expand Down
59 changes: 32 additions & 27 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package flamingo

import (
"context"
"errors"
"flag"
"fmt"
"log"
Expand Down Expand Up @@ -109,12 +110,13 @@ func NewApplication(modules []dingo.Module, options ...ApplicationOption) (*Appl
option(app)
}

var flamingoConfig arrayFlags

app.flagset = flag.NewFlagSet("flamingo", flag.ContinueOnError)
dingoTraceCircular := app.flagset.Bool("dingo-trace-circular", false, "enable dingo circular tracing")
flamingoConfigLog := app.flagset.Bool("flamingo-config-log", false, "enable flamingo config logging")
flamingoConfigCueDebug := app.flagset.String("flamingo-config-cue-debug", "", "query the flamingo cue config loader (use . for root)")
flamingoContext := app.flagset.String("flamingo-context", app.defaultContext, "set flamingo execution context")
var flamingoConfig arrayFlags
app.flagset.Var(&flamingoConfig, "flamingo-config", "add additional flamingo yaml config")
dingoInspect := app.flagset.Bool("dingo-inspect", false, "inspect dingo")

Expand Down Expand Up @@ -218,52 +220,54 @@ func (app *Application) Run() error {
return fmt.Errorf("get initialized injector: %w", err)
}

i, err := injector.GetAnnotatedInstance(new(cobra.Command), "flamingo")
instance, err := injector.GetAnnotatedInstance(new(cobra.Command), "flamingo")
if err != nil {
return fmt.Errorf("app: get flamingo cobra.Command: %w", err)
}

rootCmd := i.(*cobra.Command)
rootCmd := instance.(*cobra.Command)
rootCmd.SetArgs(app.flagset.Args())

i, err = injector.GetInstance(new(eventRouterProvider))
instance, err = injector.GetInstance(new(eventRouterProvider))
if err != nil {
return fmt.Errorf("app: get eventRouterProvider: %w", err)
}
i.(eventRouterProvider)().Dispatch(context.Background(), new(flamingo.StartupEvent))
instance.(eventRouterProvider)().Dispatch(context.Background(), new(flamingo.StartupEvent))

return rootCmd.Execute()
}

func typeName(of reflect.Type) string {
func typeName(target reflect.Type) string {
var name string

for of.Kind() == reflect.Ptr {
of = of.Elem()
for target.Kind() == reflect.Ptr {
target = target.Elem()
}

if of.Kind() == reflect.Slice {
if target.Kind() == reflect.Slice {
name += "[]"
of = of.Elem()
target = target.Elem()
}

if of.Kind() == reflect.Ptr {
if target.Kind() == reflect.Ptr {
name += "*"
of = of.Elem()
target = target.Elem()
}

if of.PkgPath() != "" {
name += of.PkgPath() + "."
if target.PkgPath() != "" {
name += target.PkgPath() + "."
}

name += of.Name()
name += target.Name()

return name
}

const truncMax = 25

func trunc(s string) string {
if len(s) > 25 {
return s[:25] + "..."
if len(s) > truncMax {
return s[:truncMax] + "..."
}
return s
}
Expand Down Expand Up @@ -297,15 +301,15 @@ func inspect(injector *dingo.Injector) {
fmt.Println("\nMultiBindings:")
injector.Inspect(dingo.Inspector{
InspectMultiBinding: func(of reflect.Type, index int, annotation string, to reflect.Type, provider, instance *reflect.Value, in dingo.Scope) {
//fmt.Printf("%d: ", index)
// fmt.Printf("%d: ", index)
printBinding(of, annotation, to, provider, instance, in)
},
})

fmt.Println("\nMapBindings:")
injector.Inspect(dingo.Inspector{
InspectMapBinding: func(of reflect.Type, key string, annotation string, to reflect.Type, provider, instance *reflect.Value, in dingo.Scope) {
//fmt.Printf("%s: ", key)
// fmt.Printf("%s: ", key)
printBinding(of, annotation, to, provider, instance, in)
},
})
Expand Down Expand Up @@ -341,7 +345,8 @@ func (a *servemodule) Inject(
a.eventRouter = eventRouter
a.logger = logger
a.server = &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Port),
Addr: fmt.Sprintf(":%d", cfg.Port),
ReadHeaderTimeout: 10 * time.Second,
}
a.configuredSampler = configuredSampler
a.publicEndpoint = cfg.PublicEndpoint
Expand All @@ -361,26 +366,26 @@ func (a *servemodule) CueConfig() string {
return `core: serve: port: >= 0 & <= 65535 | *3322`
}

func serveProvider(a *servemodule, logger flamingo.Logger) *cobra.Command {
func serveProvider(serveModule *servemodule, logger flamingo.Logger) *cobra.Command {
serveCmd := &cobra.Command{
Use: "serve",
Short: "Default serve command - starts on Port 3322",
Run: func(cmd *cobra.Command, args []string) {
a.server.Handler = &ochttp.Handler{IsPublicEndpoint: a.publicEndpoint, Handler: a.router.Handler(), GetStartOptions: a.configuredSampler.GetStartOptions()}
serveModule.server.Handler = &ochttp.Handler{IsPublicEndpoint: serveModule.publicEndpoint, Handler: serveModule.router.Handler(), GetStartOptions: serveModule.configuredSampler.GetStartOptions()}

err := a.listenAndServe()
err := serveModule.listenAndServe()
if err != nil {
if err == http.ErrServerClosed {
if errors.Is(err, http.ErrServerClosed) {
logger.Info(err)
} else {
logger.Fatal("unexpected error in serving:", err)
}
}
},
}
serveCmd.Flags().StringVarP(&a.server.Addr, "addr", "a", a.server.Addr, "addr on which flamingo runs")
serveCmd.Flags().StringVarP(&a.certFile, "certFile", "c", "", "certFile to enable HTTPS")
serveCmd.Flags().StringVarP(&a.keyFile, "keyFile", "k", "", "keyFile to enable HTTPS")
serveCmd.Flags().StringVarP(&serveModule.server.Addr, "addr", "a", serveModule.server.Addr, "addr on which flamingo runs")
serveCmd.Flags().StringVarP(&serveModule.certFile, "certFile", "c", "", "certFile to enable HTTPS")
serveCmd.Flags().StringVarP(&serveModule.keyFile, "keyFile", "k", "", "keyFile to enable HTTPS")

return serveCmd
}
Expand Down
2 changes: 1 addition & 1 deletion core/auth/debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func (c *debugController) Inject(responder *web.Responder, identityService *WebI
}

var tpl = template.Must(template.New("debug").Parse(
//language=gohtml
// language=gohtml
`
<h1>Auth Debug</h1><hr/>
<h2>Registered RequestIdentifier:</h2>
Expand Down
2 changes: 1 addition & 1 deletion core/auth/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func (p *securityRoleProvider) All(ctx context.Context, _ *web.Session) []domain
for _, identity := range p.service.IdentifyAll(ctx, request) {
_ = identity
identified = true
//if roler, ok := identity.(hasRoles); ok {
// if roler, ok := identity.(hasRoles); ok {
//roles = append(roles, roler.Roles()...)
//}
}
Expand Down
2 changes: 1 addition & 1 deletion core/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ type (
Backend interface {
Get(key string) (entry *Entry, found bool) // Get a cache entry
Set(key string, entry *Entry) error // Set a cache entry
//Peek(key string) (entry *CacheEntry, found bool) // Peek for a cache entry, this should not trigger key-updates or weight/priorities to be changed
// Peek(key string) (entry *CacheEntry, found bool) // Peek for a cache entry, this should not trigger key-updates or weight/priorities to be changed
Purge(key string) error
PurgeTags(tags []string) error
Flush() error
Expand Down
2 changes: 1 addition & 1 deletion core/cache/httpFrontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ func (hf *HTTPFrontend) load(ctx context.Context, key string, loader HTTPLoader,

span.AddAttributes(trace.StringAttribute("parenttrace", response.span.TraceID.String()))
span.AddAttributes(trace.StringAttribute("parentspan", response.span.SpanID.String()))
//span.AddLink(trace.Link{
// span.AddLink(trace.Link{
// SpanID: data.(loaderResponse).span.SpanID,
// TraceID: data.(loaderResponse).span.TraceID,
// Type: trace.LinkTypeChild,
Expand Down
2 changes: 1 addition & 1 deletion core/locale/application/date_time_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (dts *DateTimeService) Inject(

// GetDateTimeFormatterFromIsoString Need string in format ISO: "2017-11-25T06:30:00Z"
func (dts *DateTimeService) GetDateTimeFormatterFromIsoString(dateTimeString string) (*domain.DateTimeFormatter, error) {
timeResult, err := time.Parse(time.RFC3339, dateTimeString) //"2006-01-02T15:04:05Z"
timeResult, err := time.Parse(time.RFC3339, dateTimeString) // "2006-01-02T15:04:05Z"
if err != nil {
return nil, fmt.Errorf("could not parse date in defined format: %v: %w", dateTimeString, err)
}
Expand Down
10 changes: 5 additions & 5 deletions core/locale/infrastructure/translation_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,17 +61,17 @@ func (ts *TranslationService) TranslateLabel(label domain.Label) string {
ts.reloadFilesIfNecessary()
translatedString, err := ts.translateWithLib(label.GetLocaleCode(), label.GetKey(), label.GetCount(), label.GetTranslationArguments())

//while there is an error check fallBacks
// while there is an error check fallBacks
for _, fallbackLocale := range label.GetFallbackLocaleCodes() {
if err != nil {
translatedString, err = ts.translateWithLib(fallbackLocale, label.GetKey(), label.GetCount(), label.GetTranslationArguments())
}
}
if err != nil {
//default to key (=untranslated) if still an error
// default to key (=untranslated) if still an error
translatedString = label.GetKey()
}
//Fallback if label was not translated
// Fallback if label was not translated
if translatedString == label.GetKey() && label.GetDefaultLabel() != "" {
return ts.parseDefaultLabel(label.GetDefaultLabel(), label.GetKey(), label.GetTranslationArguments())
}
Expand All @@ -84,11 +84,11 @@ func (ts *TranslationService) Translate(key string, defaultLabel string, localeC
label, err := ts.translateWithLib(localeCode, key, count, translationArguments)

if err != nil {
//default to key (=untranslated) on error
// default to key (=untranslated) on error
label = key
}

//Fallback if label was not translated
// Fallback if label was not translated
if label == key && defaultLabel != "" {
return ts.parseDefaultLabel(defaultLabel, key, translationArguments)
}
Expand Down
2 changes: 1 addition & 1 deletion core/security/interface/middleware/securityMiddleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
const (
// ReferrerRedirectStrategy strategy to redirect to the supplied referrer
ReferrerRedirectStrategy = "referrer"
//PathRedirectStrategy strategy to redirect to the supplied path
// PathRedirectStrategy strategy to redirect to the supplied path
PathRedirectStrategy = "path"
)

Expand Down
2 changes: 1 addition & 1 deletion framework/cmd/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func (m *Module) Configure(injector *dingo.Injector) {
},
Example: `Run with -h or -help to see global debug flags`,
}
//rootCmd.SetHelpTemplate()
// rootCmd.SetHelpTemplate()
rootCmd.FParseErrWhitelist.UnknownFlags = true
for _, set := range flagSetProvider() {
rootCmd.PersistentFlags().AddFlagSet(set)
Expand Down
2 changes: 1 addition & 1 deletion framework/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ func TestMapMapInto(t *testing.T) {
}
}

//fill the config map according to the resultType struct
// fill the config map according to the resultType struct
m := make(Map)

assert.NoError(t, m.Add(Map{
Expand Down
6 changes: 3 additions & 3 deletions framework/config/configcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ func dumpConfigArea(a *Area) {
fmt.Println("**************************")
fmt.Println("Area: ", a.Name)
fmt.Println("**************************")
if false { //cuedump {
if false { // cuedump {
// build a cue runtime to verify the config
//cueRuntime := new(cue.Runtime)
// cueRuntime := new(cue.Runtime)
//ci, err := cueRuntime.Build(a.cueBuildInstance)
//if err != nil {
// panic(err)
Expand All @@ -71,7 +71,7 @@ func dumpConfigArea(a *Area) {
fmt.Println("")
}

//d, _ := format.Node(ci.Value().Syntax(), format.Simplify())
// d, _ := format.Node(ci.Value().Syntax(), format.Simplify())
//fmt.Println(string(d))
} else {
x, _ := json.MarshalIndent(a.Configuration, "", " ")
Expand Down
2 changes: 2 additions & 0 deletions framework/web/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ func RunWithDetachedContext(origCtx context.Context, fnc func(ctx context.Contex

request := RequestFromContext(origCtx)
session := SessionFromContext(origCtx)

if request != nil && session == nil {
session = request.Session()
}

ctx := ContextWithRequest(trace.NewContext(context.Background(), span), request)
ctx = ContextWithSession(ctx, session)

//nolint:contextcheck // we want a new context here
fnc(ctx)
}
9 changes: 5 additions & 4 deletions framework/web/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ func (fc *FilterChain) Next(ctx context.Context, req *Request, w http.ResponseWr

next := fc.filters[0]
fc.filters = fc.filters[1:]

return next.Filter(ctx, req, w, fc)
}

Expand All @@ -74,18 +75,18 @@ func (sf sortableFilers) Len() int {
}

// Less supports implementation for sort.Interface
func (sf sortableFilers) Less(i, j int) bool {
func (sf sortableFilers) Less(indexLeft, indexRight int) bool {
firstPriority := 0
if filter, ok := sf[i].filter.(PrioritizedFilter); ok {
if filter, ok := sf[indexLeft].filter.(PrioritizedFilter); ok {
firstPriority = filter.Priority()
}

secondPriority := 0
if filter, ok := sf[j].filter.(PrioritizedFilter); ok {
if filter, ok := sf[indexRight].filter.(PrioritizedFilter); ok {
secondPriority = filter.Priority()
}

return firstPriority < secondPriority || (firstPriority == secondPriority && sf[i].index > sf[j].index)
return firstPriority < secondPriority || (firstPriority == secondPriority && sf[indexLeft].index > sf[indexRight].index)
}

// Swap supports implementation for sort.Interface
Expand Down
Loading