I'm getting below error with below import code:
Code:
package main
import (
"log"
"net/http"
"os"
"github.com/emicklei/go-restful"
"github.com/emicklei/go-restful/swagger"
"./api"
)
Error:
.\main.go:9: imported and not used: "_/c_/Users/aaaa/IdeaProjects/app/src/api"
Is there a reason why the import is not working given that I have package api and files stored under api folder?
I'm using below to use api in main.go
func main() {
// to see what happens in the package, uncomment the following
restful.TraceLogger(log.New(os.Stdout, "[restful] ", log.LstdFlags|log.Lshortfile))
wsContainer := restful.NewContainer()
api := ApiResource{map[string]OxiResp{}}
api.registerLogin(wsContainer)
api.registerAccount(wsContainer)
api.registerLostLogin(wsContainer)
api.registerWallet(wsContainer)
}
The compiler looks for actual use of a package .. not the fact it exists.
You need to use something from that package.. or remove the import. E.g:
v := api.Something ...
If you don't use anything from that package in your source file .. you don't need to import it. That is, unless you want the init function to run. In which case, you can use the ignore notation import _.
EDIT:
After your update, it appears you're overwriting the package import here:
api := ApiResource{map[string]OxiResp{}}
That declares a variable called api. Now the compiler thinks its a variable, and so you're not actually using the api package.. you're using the api variable.
You have a few options.
Firstly, you can call that variable something else (probably what I would do):
apiv := ApiResource{map[string]OxiResp{}}
Or, alias your import (not what I would do.. but an option nonetheless):
import (
// others here
api_package "./api"
)
The problem is that the compiler is confused on what to use. The api package.. or the api variable you have declared.
You should also import the package via the GOPATH instead of relatively.
First of all, don't use relative imports.
If your GOPATH contains /Users/aaaa/IdeaProjects/app/src, then import your package as api.
Next, you're shadowing api with the assignment to api :=. Use a different name.
This error can occur if your .go file has an error that is preventing the compiler from reaching the location where it is used.
Related
I have following folder structure here
server
-main.go
-cmd
-config
-config.go
-handlerr.go
-handlers
-handlers.go
-pkg
-models
-models.go
-db
-db.go
-router
-router.go
and when I am trying to import the "models package" into db package it says "invalid import path:...",this structure i am following with book ,so what am i doing wrong ?How do i import the models into db functions or should i replace them (db and models),any suggest?
enter image description here
Here are the files in the question filled out. The import from db to models is illustrated. I set the module name to "my.example". Change that name to meet your needs. It's best to pick something including a "." to avoid conflict with a standard package. You can run this code on the Go PlayGround. How to Write Go Code explains all of this stuff in detail.
-- main.go --
package main
import (
"my.example/pkg/models/db"
)
func main() {
db.Hello()
}
-- go.mod --
module my.example
-- cmd/config/config.go --
package config
-- cmd/config/handlerr.go --
package config
-- handlers/handlers.go --
package handlers
-- pkg/models/models.go --
package models
func Hello() string { return "hello from models" }
-- pkg/models/db/db.go --
package db
import (
"fmt"
"my.example/pkg/models"
)
func Hello() {
fmt.Println("hello from db and", models.Hello())
}
-- pkg/router/router.go --
package router
Regarding the layout of the files: This is in the land of opinions, so I will just ask you a question. Does the extra level of nesting in the pkg and cmd gain you anything?
UPDATE:
As #maxm reminded me, use GOPATH, here is a great example, that he mentioned.
So, if my web search and a little example program are correct, this is pretty much what is happening here.
Golang sees local packages as folders with .go files, on practice /modules/module.go if modules.go has package modules on the 1st line.
So, when we are including a local package, we are actually including a folder. I created a little example:
/project
main.go
/modules
modules.go
/printer
printer.go
main.go
package main
import (
"./modules/printer"
)
func main() {
printer.Print()
}
modules/modules.go
package modules
import (
"fmt"
)
func Modules() {
fmt.Println("Modules Package")
}
modules/printer/printer.go
package printer
import (
"../../modules"
)
func Print() {
modules.Modules()
}
And this actually works! So, you can import a parent module, you just need to include the folder.
Of course, we cannot have import cycle, Golang won't allow it and if you are having this kind of error, it's better to change the structure of your program.
I'm not talking about paths and stuff, it's just a practical solution. So, smart people, please correct me!
I'm new with Go and I'm trying to build an API, but I'm having some problems at importing functions located at another local package.
My folder structure looks like the following:
├── app.go //at package "main"
└── middleware
├── authentication.go // package "middleware"
I'm trying to import the functions inside the authentication.go file like that:
package main
import (
"fmt"
"log"
"net/http"
"./middleware" //Also tried "middleware"
)
Thinking that's an import problem because if I move the functions to the same package and folder, it works fine.
The func I'm trying to use also starts with caps, so there shouldn't be a problem importing it:
func AuthMiddleware(next http.Handler) http.Handler {
//...
}
What's wrong with my code? Also, what's the best way to import a local package without having to write the whole path?
I'm using Go 1.15.2, and checked all related S.O posts, but none looks to solve my problem.
EDIT :
Whenever you use a function located at another package, you have to refer first to the package. I was trying to call my function as AuthMiddleware(parameters) but the right way to call it was middleware.AuthMiddleware(parameters).
Don't use dot import paths like this, it is not recommended. Use the relative path for your go src dir (which can be local only, it doesn't have to be online) and it'll work fine.
So something like
import "me.com/api/middleware"
Then to avoid stutter perhaps:
middleware.Auth()
There is two way to call function from another package
You can use package or alias to call function
With package name
package main
import (
"./middleware"
)
middleware.Auth();
With alias
package main
import (
mid "./middleware"
)
mid.Auth();
You can import whole package by using . , after that you do not need to use alias or package name to call function. You can use call function directly with function name
package main
import (
. "./middleware"
)
Auth();
Intro
I'm trying to import my EventController.go to my main.go file.
Directory:
├───Controllers
│ └───Event
│ └───EventController.go
├───Models
├───Routes
│
└ Main.go
Problem:
import (
"log"
"net/http"
_ "/Controllers/Event/EventController.go" //problem here
)
error : cannot import absolute path
I read some documentation but the thing is I see that I'm doing it correctly, though i learnt about $GOPATH but I want to use the local directory thing.
What am I doing wrong and what's this error about
NOTE: I want add that I'm using windows as os
Thank you.
There are a few issues:
Packages are imported, not files (as noted in other answers)
File absolute import paths are not valid as the error states. An application can use file relative import paths (the path starts with "./") or a path relative to the Go workspace. See the go command doc for info on the syntax. Import paths relative to the Go workspace are the preferred form.
It is idiomatic to use lowercase names for packages (and their corresponding directories). The camel case names in the question are workable, but it's better to go with the flow.
The document How to Write Go Code is a nice tutorial on how to do this.
Here's how to reorganize the code given the above. This assumes that main.go is in a package with import path "myapp". Change this import path to whatever you want.
-- main.go --
package main
import (
"log"
_ "myapp/controllers/event"
)
func main() {
log.Println("hello from main")
}
-- go.mod --
module myapp
-- controllers/event/eventController.go --
package event
import "log"
func init() {
log.Println("hello from controllers/event")
}
Run this example on the Go playground.
You cannot import a file. You can import a package. So, lets say your main is the package "github.com/mypackage", then you should import "github.com/mypackage/Controllers/Event".
Go supports package level import. You can import a package by adding it to the import statement at the beginning of the file.
In your case, you should do something like this-
import (
"log"
"net/http"
"Controllers/Event/EventController"
)
Also, you should remove first "/" from the file name
_ /Controllers/Event/EventController.go" //problem here
because your Controllers folder is at the same level as Main.go file. You should always give relative path in the import statements.
In this way, you can use any file which is listed under EventController folder.
I am trying to get a function from the package ModelT into my Controllers package . I have looked at the example on Call a function from another package in Go however it is not working. This is my simple code
package ModelT
-- Print.go
func PrintMe() string {
return "hello"
}
package Controllers
-- Circle.go
import ("Yislyapp/ModelT") -- This does not work
func Circle_List() {
ModelT.PrintMe()
}
My small program won't compile either saying: can not resolve directory yislyapp . I get the samething even if I change it to Yisly-Backend/ModelT or Yisly-Backend./ModelT , it seems like it can't find the package. Any suggestions would be great since i'm starting out. If I put it into my Go file Home.go then it works
import (
"./ModelT"
)
func main() {
ModelT.PrintMe() -- This works in my Home.go file
}
You should set the GOPATH environment variable to the root of your Go project. Your source code should then be somewhere under $GOPATH/src. The import path for a package is the path to the package's directory relative to $GOPATH/src. See https://golang.org/doc/code.html for more info.
I try to call the ExpFloat64() function of the rand package (http://golang.org/pkg/rand/). However, it gives following error "prog.go:4: imported and not used: rand prog.go:7: undefined: ExpFloat64". Can anybody help me why is it giving error ? Code given below.
package main
import "fmt"
import "rand"
func main() {
fmt.Println(ExpFloat64())
}
The error message explains it perfectly - in Go, you can't import packages and not use them. Here, it says you're importing rand and not using it, so either use it or don't import it. Your main function should be:
fmt.Println(rand.ExpFloat64())
To add to what Chris Bunch said, if you really wanted to use the names in the package (e.g. ExpFloat64) directly without using the package name, you can do this:
import . "rand"