could not build arguments for function - go

I am trying to build go application using DI but since I just started to learn how to do this I am facing problem as below
"could not build arguments for function "github.com/pharmeasy/kite/service/handlers".CreateExperiment.func1 (/Users/sahilpaudel/Documents/PharmEasy/Go/kite/service/handlers/experiment.go:62): failed to build *repository.ExperimentRepository: missing dependencies for function "github.com/pharmeasy/kite/core/dao/repository".NewExperimentRepository (/Users/sahilpaudel/Documents/PharmEasy/Go/kite/core/dao/repository/experiment.go:16): missing type: *string"
repository looks like this
type ExperimentRepository struct {
dbName *string
}
// NewExperimentRepository returns new ExperimentDao
func NewExperimentRepository(dbName *string) *ExperimentRepository {
return &ExperimentRepository{ dbName: dbName }
}
func (expRepo *ExperimentRepository) Create(experiment *models.Experiment) error {
return nil
}
DI looks like this
func buildContainer() *dig.Container {
container := dig.New()
_ = container.Provide(config.NewConfig)
_ = container.Provide(database.GetInstance)
_ = container.Provide(repository.NewExperimentRepository)
return container
}
And I am trying to use it here as
di := container.GetInstance()
err = di.Invoke(func(experimentRepo *repository.ExperimentRepository) {
err := experimentRepo.Create(&experiment)
if err != nil {
utils.RespondError(res, err, http.StatusInternalServerError)
return
}
})
Stucks since morning and but couldn't figure out whats the issue here.

Related

Go lang type assertion

I am trying to do dependency injection in golang with applying dependency inversion principle, so I have the following service
package account
import (
types "zaClouds/modules/account/domain/types"
"zaClouds/modules/shared"
)
type IPlanDomainService interface {
GetUsagePlanById(string) *shared.Result[types.UsagePlan]
}
type PlanDomainService struct {
usagePlanService types.IUsagePlanService
}
func (planDomainService *PlanDomainService) GetUsagePlanById(id string) *shared.Result[types.UsagePlan] {
result := &shared.Result[types.UsagePlan]{}
usagePlanResult := planDomainService.usagePlanService.GetPlanById(id)
if usagePlanResult.Err != nil {
result.Err = usagePlanResult.Err
return result
}
result.Data = usagePlanResult.Data
return result
}
func PlanDomainServiceFactory(usagePlanService types.IUsagePlanService) IPlanDomainService {
return &PlanDomainService{usagePlanService: usagePlanService}
}
as you can see, it accepts another service with type IUsagePlanService
and here is the interface for it
package account
import (
"zaClouds/modules/shared"
"github.com/shopspring/decimal"
)
type UsagePlan struct {
ID string
Title string
Description interface{}
PlanID string
Price decimal.Decimal
Duration int
Features map[string]map[string]string
}
type IUsagePlanService interface {
GetPlanById(string) *shared.Result[UsagePlan]
}
and here is the way I am injecting this service to domain service
func DiInit(usagePlanService interface{}) domainServices.IPlanDomainService {
domainServices.PlanDomainServiceFactory(types.IUsagePlanService(usagePlanService))
return domainServices.PlanDomainServiceFactory(usagePlanService.(types.IUsagePlanService))
}
as you can see, I am trying to do a type assertion but it doesn't work, and gives me the following error:
panic: interface conversion: *usagePlan.UsagePlanRepository is not account.IUsagePlanService: missing method GetPlanById
Edit
Here is the actual implementation for usagePlanService
type IUsagePlanRepository interface {
createClient(string) *http.Request
GetPlanById(string) *shared.Result[usagePlanRepoModels.UsagePlan]
}
type UsagePlanRepository struct {
plansEndpoint string
httpClient *http.Client
}
func (r *UsagePlanRepository) GetPlanById(id string) *shared.Result[usagePlanRepoModels.UsagePlan] {
result := &shared.Result[usagePlanRepoModels.UsagePlan]{}
req := r.createClient(id)
resp, err := r.httpClient.Do(req)
if err != nil {
log.Println("failed to load plan details \n[ERROR]", err)
result.Err = err
return result
}
defer func() {
bodyError := resp.Body.Close()
if bodyError != nil {
result.Err = bodyError
}
}()
if result.Err != nil {
return result
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
utils.Logger.Error("failed to load plan details \n[ERROR]", err, nil)
result.Err = err
return result
}
if resp.StatusCode >= 400 {
result.Err = errors.New(string(body))
utils.Logger.Info("getPlanById", string(body))
}
getUsagePlanResponse, foundError := usagePlanRepoModels.CreateGetUsagePlanResponse(body)
if foundError != nil {
result.Err = foundError
return result
}
result.Data = *getUsagePlanResponse
return result
}
When using an interface, you need to define all functions that you will use with the same name and signature as the implementation.
The error message you got indicates that the implementation and the interface are different.
The implementation is not shown in your question, but you defined the function for your interface like this: GetPlanById(string) *shared.Result[UsagePlan]. Any deviation from it will result in error. One common mistake is with the pointers. Adding or removing the * to the return type will incur in error if it differs from the original.
Edit:
Your interface should look like this:
type IUsagePlanService interface {
GetPlanById(id string) *shared.Result[usagePlanRepoModels.UsagePlan]
}
If your function is returning a private type, and you can change that, you should. If you cant change it, than you should create a function that wraps the function you are trying to abstract with the interface.

How to test uber dig application Golang

I recently wanted to try out dependency injection in golang and I picked up Uber dig container everything working well but I am not sure how to test my code.
My dig container
func buildContainer() *dig.Container {
container := dig.New()
_ = container.Provide(config.GetInstance)
_ = container.Provide(database.GetInstance)
_ = container.Provide(evaluation.NewEvaluator)
_ = container.Provide(repository.NewExperimentRepository)
return container
}
My Dao
type ExperimentDao interface {
// Create experiment
Create(experiment *models.Experiment) error
// Update experiment
Update(experiment *models.Experiment) error
// FindByID find experiment by id
FindByID(id string) (*models.Experiment, error)
//FindAll find all the questions
FindAll(filter bson.M, page int, limit int) (*models.ExperimentPagination, error)
}
My Repository that implements the doa interface
type ExperimentRepository struct {
DB *database.DB
}
// NewExperimentRepository returns new ExperimentDao
func NewExperimentRepository(db *database.DB) interfaces.ExperimentDao {
return &ExperimentRepository{DB: db}
}
func (expRepo *ExperimentRepository) Create(experiment *models.Experiment) error {
//repository code to insert in DB
}
// rest of the implemented func(s)
Here is my handler where I use the injected Repository to insert the data
func CreateExperiment(res http.ResponseWriter, req *http.Request) {
experiment := models.Experiment{}
err := json.NewDecoder(req.Body).Decode(&experiment)
if err != nil {
logrus.Error("Create Experiment Error parsing payload : ", err)
utils.RespondError(res, err, 400)
return
}
ValErr := ValidateExpt(experiment, "create")
if ValErr != "" {
logrus.Error("Create Experiment Error : ", ValErr)
utils.Respond(res, ValErr, 400)
return
}
di := container.GetInstance()
err = di.Invoke(func(dao interfaces.ExperimentDao) {
err := dao.Create(&experiment)
if err != nil {
utils.RespondError(res, err, http.StatusInternalServerError)
return
}
utils.Respond(res, "experiment created successfully", http.StatusOK)
})
if err != nil {
logrus.Error("Insert Experiment Error : ", err)
utils.RespondError(res, err, 400)
}
}
// Di builder
func GetInstance() *dig.Container {
once.Do(func() {
container = buildContainer()
})
return container
}
Now as the code is working fine as expected so I hope the approach is correct as per my knowledge but now I am unable to figure out how to write the test to test this code I can write few validations for experiment model but not for repository, dao or the di container.
Can you guys help where should I look or what am I missing.
Thanks.
I would suggest you to write a function, that will receive all dependencies as parameters and will return the HTTP handler, like this:
func NewCreateExperimentHandler(c *dig.Container) http.HandlerFunc {
return func (res http.ResponseWriter, req *http.Request) {
// the current CreateExperiment() implementation
}
}
This will allow you to mock your container inside the tests.

Error while trying to fetch queryresult.KV object in JSON.Unmarshal

I am a little bit confused here and although I have searched a lot on this, something is clearly missing from my knowledge and I am asking your help.
I have created a Hyperledger Fabric Network and installed a chaincode in it. And I want to make a function that retrieves all the World State inputs about the Keys. I have done it already with the bytes.Buffer and it worked. But what I want to do is to do it with a struct.
So, I created the following struct that has only the key:
type WSKeys struct {
Key string `json: "key"`
Namespace string `json: "Namespace"`
}
And this is my code function:
func (s *SmartContract) getAllWsDataStruct(APIstub shim.ChaincodeStubInterface , args []string) sc.Response {
var keyArrayStr []WSKeys
resultsIterator, err := APIstub.GetQueryResult("{\"selector\":{\"_id\":{\"$ne\": null }} }")
if err != nil {
return shim.Error("Error occured when trying to fetch data: "+err.Error())
}
for resultsIterator.HasNext() {
// Get the next record
queryResponse, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
fmt.Println(queryResponse)
var qry_key_json WSKeys
json.Unmarshal([]byte(queryResponse), &qry_key_json)
keyArray = append(keyArray, qry_key_json)
}
defer resultsIterator.Close()
all_bytes, _ := json.Marshal(keyArray)
fmt.Println(keyArray)
return shim.Success(all_bytes)
}
When executing the above I get the following error:
cannot convert queryResponse (type *queryresult.KV) to type []byte
I can get the results correctly if I, for example do this:
func (s *SmartContract) getAllWsDataStruct(APIstub shim.ChaincodeStubInterface , args []string) sc.Response {
var keyArray []string
resultsIterator, err := APIstub.GetQueryResult("{\"selector\":{\"_id\":{\"$ne\": null }} }")
if err != nil {
return shim.Error("Error occured when trying to fetch data: "+err.Error())
}
for resultsIterator.HasNext() {
// Get the next record
queryResponse, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
fmt.Println(queryResponse)
keyArray = append(keyArray, queryResponse.Key)
}
defer resultsIterator.Close()
all_bytes, _ := json.Marshal(keyArray)
fmt.Println(keyArray)
return shim.Success(all_bytes)
}
But, why I get the above error when trying to add the queryResponse into a custom struct?
Do I need to add it to a struct that is only its type?
Please someone can explain what I am missing here?
The error statement is verbose enough to indicate, that your []byte conversion failed for the type queryResponse which, with a bit of lookup seems to be a struct type. In Go you cannot natively convert a struct instance to its constituent bytes without encoding using gob or other means.
Perhaps your intention was to use the Key record in the struct for un-marshalling
json.Unmarshal([]byte(queryResponse.Key), &qry_key_json)

Generic function with variable input/output types

Just playing with aws sdk for go. When listing resources of different types I tend to have alot of very similar functions like the two in the example bellow.
Is there a way to rewrite them as one generic function that will return a specific type depending on what is passed on as param?
Something like:
func generic(session, funcToCall, t, input) (interface{}, error) {}
currently I have to do this (functionality is the same just types change):
func getVolumes(s *session.Session) ([]*ec2.Volume, error) {
client := ec2.New(s)
t := []*ec2.Volume{}
input := ec2.DescribeVolumesInput{}
for {
result, err := client.DescribeVolumes(&input)
if err != nil {
return nil, err
}
t = append(t, result.Volumes...)
if result.NextToken != nil {
input.NextToken = result.NextToken
} else {
break
}
}
return t, nil
}
func getVpcs(s *session.Session) ([]*ec2.Vpc, error) {
client := ec2.New(s)
t := []*ec2.Vpc{}
input := ec2.DescribeVpcsInput{}
for {
result, err := client.DescribeVpcs(&input)
if err != nil {
return nil, err
}
t = append(t, result.Vpcs...)
if result.NextToken != nil {
input.NextToken = result.NextToken
} else {
break
}
}
return t, nil
}
Because you only deal with functions it is possible to use the reflect package to generate functions at runtime.
Using the object type (Volume, Vpc) it is possible to derive all subsequents information to provide a fully generic implementation that is really dry, at the extent at the being more complex and slower.
It is untested, you are welcome to help in testing and fixing it, but something like this should put you on the track
https://play.golang.org/p/mGjtYVG2OZS
The registry idea come from this answer https://stackoverflow.com/a/23031445/4466350
for reference the golang documentation of the reflect package is at https://golang.org/pkg/reflect/
package main
import (
"errors"
"fmt"
"reflect"
)
func main() {
fmt.Printf("%T\n", getter(Volume{}))
fmt.Printf("%T\n", getter(Vpc{}))
}
type DescribeVolumesInput struct{}
type DescribeVpcs struct{}
type Volume struct{}
type Vpc struct{}
type Session struct{}
type Client struct{}
func New(s *Session) Client { return Client{} }
var typeRegistry = make(map[string]reflect.Type)
func init() {
some := []interface{}{DescribeVolumesInput{}, DescribeVpcs{}}
for _, v := range some {
typeRegistry[fmt.Sprintf("%T", v)] = reflect.TypeOf(v)
}
}
var errV = errors.New("")
var errType = reflect.ValueOf(&errV).Elem().Type()
var zeroErr = reflect.Zero(reflect.TypeOf((*error)(nil)).Elem())
var nilErr = []reflect.Value{zeroErr}
func getter(of interface{}) interface{} {
outType := reflect.SliceOf(reflect.PtrTo(reflect.TypeOf(of)))
fnType := reflect.FuncOf([]reflect.Type{reflect.TypeOf(new(Session))}, []reflect.Type{outType, errType}, false)
fnBody := func(input []reflect.Value) []reflect.Value {
client := reflect.ValueOf(New).Call(input)[0]
t := reflect.MakeSlice(outType, 0, 0)
name := fmt.Sprintf("Describe%TsInput", of)
descInput := reflect.New(typeRegistry[name]).Elem()
mName := fmt.Sprintf("Describe%Ts", of)
meth := client.MethodByName(mName)
if !meth.IsValid() {
return []reflect.Value{
t,
reflect.ValueOf(fmt.Errorf("no such method %q", mName)),
}
}
for {
out := meth.Call([]reflect.Value{descInput.Addr()})
if len(out) > 0 {
errOut := out[len(out)-1]
if errOut.Type().Implements(errType) && errOut.IsNil() == false {
return []reflect.Value{t, errOut}
}
}
result := out[1]
fName := fmt.Sprintf("%Ts", of)
if x := result.FieldByName(fName); x.IsValid() {
t = reflect.AppendSlice(t, x)
} else {
return []reflect.Value{
t,
reflect.ValueOf(fmt.Errorf("field not found %q", fName)),
}
}
if x := result.FieldByName("NextToken"); x.IsValid() {
descInput.FieldByName("NextToken").Set(x)
} else {
break
}
}
return []reflect.Value{t, zeroErr}
}
fn := reflect.MakeFunc(fnType, fnBody)
return fn.Interface()
}
Proxying 3rd party API, is quite simple to implement with
go, here is how' it got implemented with endly e2e test runner AWS proxy
I would say that AWS API is perfect candidate for proxying, as long as reflection performance price is not an issue.
Some other 3rd party API like kubernetes
are much more challenging, but still quite easy to proxy with go, which is a combination of reflection and code generation:

Interface/Struct "Does not implement X, Wrong type or Method, not sure why I am getting this error

Hi guys fairly new to Golang, I understand that interfaces are kind of like contracts that guarantee that certain things will operate a certain way, thats cool and all, and if I make a local copy of it I can basically re-write how it operates (From what I understand, please correct me if I'm wrong)
Here is what I have so far
package register
import (
"log"
"net/http"
"github.com/yohcop/openid-go"
)
var nonceStore = &openid.SimpleNonceStore{
Store: make(map[string][]*openid.Nonce)}
var discoveryCache = &SimpleDiscoveryCache{}
type DiscoveredInfo interface {
OpEndpoint() string
OPLocalID() string
ClaimedID() string
}
type SimpleDiscoveredInfo struct {
opEndpoint, opLocalID, claimedID string
}
type SimpleDiscoveryCache map[string]DiscoveredInfo
func (s *SimpleDiscoveryCache) Put(id string, info DiscoveredInfo) {
db := common.ConnectDB()
rows, err := db.Query("INSERT INTO discovery_cache SET id=?, opendpoint=?, oplocalid=?, claimedid=?",
id, info.OpEndpoint(), info.OPLocalID(), info.ClaimedID())
if err != nil {
panic("Error: " + err.Error())
}
log.Println(rows)
}
func (s *SimpleDiscoveryCache) Get(id string) DiscoveredInfo {
db := common.ConnectDB()
rows, err := db.Query("SELECT FROM discovery_cache WHERE id=?", id)
if err != nil {
panic("Error: " + err.Error())
}
log.Println(rows)
var opEndpoint, opLocalID, claimedID string
for rows.Next() {
err := rows.Scan(&opEndpoint, &opLocalID, &claimedID)
if err != nil {
panic("Help!")
}
}
return &SimpleDiscoveredInfo{
opEndpoint, opLocalID, claimedID,
}
}
func DiscoverHandler(w http.ResponseWriter, r *http.Request) {
url, err := openid.RedirectURL("http://steamcommunity.com/openid", "http://localhost:1337/login/return", "http://localhost")
if err != nil {
http.Error(w, "Failed to login", 500)
}
http.Redirect(w, r, url, 303)
}
func CallbackHandler(w http.ResponseWriter, r *http.Request) {
fullUrl := "http://localhost:1337" + r.URL.String()
id, err := openid.Verify(fullUrl, discoveryCache, nonceStore)
if err != nil {
http.Error(w, "Failed", 500)
}
log.Println(id)
}
Basically I am trying to make my own DiscoveryCache so that it uses a database instead of memory for storage (as instructed to do by the Go-OpenID package located here: https://github.com/yohcop/openid-go
The part I'm trying to recreate is located here: https://github.com/yohcop/openid-go/blob/master/discovery_cache.go
Now I have done (what I assume) everything that should need doing to make this work, but I keep getting this error:
controllers/register/register.go:60: cannot use SimpleDiscoveredInfo literal (type *SimpleDiscoveredInfo) as type openid.DiscoveredInfo in return argument:
*SimpleDiscoveredInfo does not implement openid.DiscoveredInfo (missing ClaimedID method)
controllers/register/register.go:78: cannot use discoveryCache (type *SimpleDiscoveryCache) as type openid.DiscoveryCache in argument to openid.Verify:
*SimpleDiscoveryCache does not implement openid.DiscoveryCache (wrong type for Put method)
have Put(string, DiscoveredInfo)
want Put(string, openid.DiscoveredInfo)
If anybody could inform me on what I have done wrong that would be much appreciated. Thanks! If you need any more information please let me know.
SimpleDiscoveredInfo doesn't implement the interface's methods, you need something like this:
func (sdi *SimpleDiscoveredInfo) OpEndpoint() string { return sdi.opEndpoint }
func (sdi *SimpleDiscoveredInfo) OpLocalID() string { return sdi.opLocalID }
func (sdi *SimpleDiscoveredInfo) ClaimedID() string { return sdi.claimedID }
var _ openid.DiscoveredInfo = (*SimpleDiscoveredInfo)(nil)
http://play.golang.org/p/qVTTKfhNHu
For
controllers/register/register.go:78: cannot use discoveryCache (type *SimpleDiscoveryCache) as type openid.DiscoveryCache in argument to openid.Verify:
*SimpleDiscoveryCache does not implement openid.DiscoveryCache (wrong type for Put method)
have Put(string, DiscoveredInfo)
want Put(string, openid.DiscoveredInfo)
Your types need to return openid.DiscoveredInfo not DiscoveredInfo.

Resources