go-kod/kod

component was not registered

Closed this issue · 4 comments

  • environments
macOS 11.7.10
go v1.22.4
kod v0.9.1
  • pkg/infra/db/db.go
package db

import (
	"context"
	"database/sql"

	"github.com/go-kod/kod"
	"github.com/go-kod/kod/ext/client/ksql"
)

type DBComponent struct {
	kod.Implements[Component]
	kod.WithConfig[config]

	db *sql.DB
}

type config struct {
	DbConfig ksql.Config
}

func (ins *DBComponent) Init(ctx context.Context) error {
	ins.db = ins.Config().DbConfig.Build()
	return nil
}
  • demo.go
type demoImpl struct {
	kod.Implements[kod.Main]
	db kod.Ref[db.DBComponent]
}

func main() {
		fmt.Println("demo called")
		kod.Run(context.Background(), func(ctx context.Context, impl *demoImpl) error {
			dbIns := impl.db.Get()
			impl.L(ctx).Info(dbIns.Config().DbConfig.DriverName)
			return nil
		})
}
  • run
kod struct2interface ./...
kod generate ./...
  • result
Error: component implementation struct cmd.demoImpl has field kod.Ref[github.com/leopku/emeraldpanel/pkg/infra/db.DBComponent], but component db.DBComponent was not registered; maybe you forgot to run 'kod generate'

Any advice?

Please check if pkg/infra/db/kod_gen.go generated?

Maybe you could also try run kod generate -s ./... instead.

same issue after running kod generate -s ./....

  • kod_gen.go
// Code generated by "kod generate". DO NOT EDIT.
//go:build !ignoreKodGen

package db

import (
	"context"
	"github.com/go-kod/kod"
	"github.com/go-kod/kod/interceptor"
	"reflect"
)

func init() {
	kod.Register(&kod.Registration{
		Name:      "wdwow.eu.org/leo/emeraldpanel/pkg/infra/db/Component",
		Interface: reflect.TypeOf((*Component)(nil)).Elem(),
		Impl:      reflect.TypeOf(DBComponent{}),
		Refs:      ``,
		LocalStubFn: func(ctx context.Context, info *kod.LocalStubFnInfo) any {
			interceptors := info.Interceptors
			if h, ok := info.Impl.(interface {
				Interceptors() []interceptor.Interceptor
			}); ok {
				interceptors = append(interceptors, h.Interceptors()...)
			}

			return component_local_stub{
				impl:        info.Impl.(Component),
				interceptor: interceptor.Chain(interceptors),
				name:        info.Name,
			}
		},
	})
}

// kod.InstanceOf checks.
var _ kod.InstanceOf[Component] = (*DBComponent)(nil)

// Local stub implementations.

type component_local_stub struct {
	impl        Component
	name        string
	interceptor interceptor.Interceptor
}

// Check that component_local_stub implements the Component interface.
var _ Component = (*component_local_stub)(nil)

kod.Ref only supports interface, instead of struct 😀

Change db.DBComponent to db.Component would fix it.