[英]How in Golang use struct in other package file?
I am new in Golang and need some help. 我是Golang的新手 ,需要帮助。
As you can see in the code below I am tring to create REST API in Golang. 如您在下面的代码中看到的,我正试图在Golang中创建REST API。 I use mux
(Gorilla Mux) and pq
(PostgreSQL driver) as third party libraries. 我使用mux
(大猩猩Mux)和pq
(PostgreSQL驱动程序)作为第三方库。 Don't want to use ORM. 不想使用ORM。
Inside application.go
file I have InitializeRoutes
function with a list of all aviable routes. 在application.go
文件中,我具有带有所有可用路由列表的InitializeRoutes
函数。 GetFactors
function process one of these routes. GetFactors
函数处理这些路由之一。 I am tring to define GetFactors
function logic in other file called factors.go
. 我特林定义GetFactors
在调用的其他文件中的函数逻辑factors.go
。 Inside factors.go
file I want to use Application
struct which was defined in application.go
. 里面factors.go
文件我想使用Application
其在定义结构application.go
。 How to make it correctly? 如何正确制作? Right now as you can see they are in different packages. 现在,您可以看到它们位于不同的软件包中。 For thats why factors.go
file don't see Application
struct. 因此, factors.go
文件没有看到Application
结构。
Project structure : 项目结构 :
main.go
application.go
controllers
factors.go
main.go: main.go:
package main
func main() {
application := Application{}
application.Initialization()
application.Run("localhost:8000")
}
application.go : application.go :
package main
import (
"database/sql"
"github.com/gorilla/mux"
"log"
"net/http"
"rest-api/configurations"
)
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", application.GetFactors).Methods("GET")
// other code
}
controllers/factors.go : controllers / factors.go :
package controllers
import (
"net/http"
)
func (application *Application) GetFactors(rw http.ResponseWriter, request *http.Request) {
// code
}
Well, finally I decided to redesign the project structure. 好吧,最后我决定重新设计项目结构。
main.go
routes
routes.go
controllers
factors.go
models
factors.go
main.go : main.go :
import (
"your_project_name/routes"
)
func main() {
// code
router := mux.NewRouter()
routes.Use(router)
// code
}
routes/routes.go : routes / routes.go :
package routes
import (
"github.com/gorilla/mux"
"your_application_name/controllers"
)
func Use(router *mux.Router) {
router.HandleFunc("/api/factors", controllers.GetFactors).Methods("GET")
}
controllers/factors.go : controllers / factors.go :
package controllers
var GetFactors = func(res http.ResponseWriter, req *http.Request) {
// code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.