Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go import local package

Tags:

go

I have a main.go

package main

import (
    "context"
    "fmt"
    "log"

    model "model"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func handler(...){
}

I try to import model which is in the directory model and the file is called model.go

It just contains:

package model

type xxx struct {
    xxx
}

I try to import this in the main but I have the error:

build: cannot load model: cannot find module providing package model
like image 385
mealesbia Avatar asked Jan 25 '23 05:01

mealesbia


1 Answers

If your module model is not local then you can use Tonys answer and it will work fine but if you are using this module locally then you will need to add the paths in your go.mod file.

So for example, Local module model contains only model.go which has the following content

package model

type Example struct {
    Name string
}

func (e *Example) Foo() string {
    return e.Name
}

For this local module must have have to init the module with the command go mod init model and the content of the ./model/go.mod will be

module model
go 1.13

In the main module in which you are importing this module you need to add the following line

require model v1.0.0
replace model v1.0.0 => {Absolute or relative path to the model module}

So, your main testing module's go.mod file will look like this

module main

require model v1.0.0
replace model v1.0.0 => ./model

go 1.13

By setting this up you can use this module in this test module with just import "model"

Hence when testing the module with the main method

package main

import (
    model "model"
)

func main() {
    example := model.Example{
        Name: "Hello World",
    }
    println(example.Foo())
}

The output will be

Hello World
like image 196
Hamza Anis Avatar answered Feb 08 '23 21:02

Hamza Anis