Answer the question
In order to leave comments, you need to log in
How to correctly use structures in files of the same package?
Hello comrades! Please help me figure it out.
I'm trying to create a REST API in Golang. I use third party packages mux
( Gorilla Mux ) and pq
( PostgreSQL driver ) for this purpose. ORM is not going to use.
Faced the following problem. In the factors.go file, I am trying to use the Application structure , which was described in the application.go file . The files factors.go and application.go belong to the same package. How to call the GetFactors function in the application.go file? How to use the structure correctly in the factors.go fileapplication ? Perhaps a redesign is needed?
The project structure looks like this :
main.go
application.go
controllers
factors.go
package main
func main() {
application := Application{}
application.Initialization()
application.Run("localhost:8000")
}
package main
import (
"database/sql"
"github.com/gorilla/mux"
"log"
"net/http"
"rest-api/configurations"
"rest-api/controllers"
)
type Application struct {
Router *mux.Router
Database *sql.DB
}
func (application *Application) Initialization() {
var err error
application.Database, err = configurations.DatabaseConnection()
if err != nil {
log.Fatal(err)
}
application.Router = mux.NewRouter()
application.Router.StrictSlash(true)
application.InitializeRoutes()
}
func (application *Application) Run(address string) {
log.Fatal(http.ListenAndServe(address, application.Router))
}
func (application *Application) InitializeRoutes() {
application.Router.HandleFunc("/api/factors", controllers.GetFactors).Methods("GET")
// Остальной код
}
package main
import (
"net/http"
)
func (application *Application) GetFactors(rw http.ResponseWriter, request *http.Request) {
// Остальной код
}
Answer the question
In order to leave comments, you need to log in
`factors.go` cannot be part of the `main` package, as it is in the `controllers` package.
And there is a suspicion that the code will not build anyway, since the `main` module in the `application.go` file depends on the `controllers` module of the `factors.go` file, while the `controllers` module in the `factors.go` file depends on the `main` module of `application.go`. It turns out recursion, and the code will not be able to assemble.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question