-2
我有兩個文件main.go
和group.go
...它看起來像這樣遇到問題分裂代碼走在多個文件中
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
// Creates a gin router with default middlewares:
// logger and recovery (crash-free) middlewares
router := gin.Default()
v1 := router.Group("/v1")
{
v1.GET("/", func (c *gin.Context) {
c.JSON(http.StatusOK, "{'sup': 'dup'}")
})
groups := v1.Group("/groups")
{
groups.GET("/", groupIndex)
groups.GET("/:id", groupShow)
groups.POST("/", groupCreate)
groups.PUT("/:id", groupUpdate)
groups.DELETE("/:id", groupDelete)
}
}
// Listen and server on 0.0.0.0:8080
router.Run(":3000")
}
所以方法groupIndex
,groupCreate
,groupUpdate
等位於另一個文件routes/group.go
下
package main
import (
"strings"
"github.com/gin-gonic/gin"
)
func groupIndex(c *gin.Context) {
var group struct {
Name string
Description string
}
group.Name = "Famzz"
group.Description = "Jamzzz"
c.JSON(http.StatusOK, group)
}
func groupShow(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupShow': 'someContent'}")
}
func groupCreate(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupShow': 'someContent'}")
}
func groupUpdate(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupUpdate': 'someContent'}")
}
func groupDelete(c *gin.Context) {
c.JSON(http.StatusOK, "{'groupDelete': 'someContent'}")
}
但是,當我嘗試編譯我收到以下錯誤
stuff/main.go:21: undefined: groupIndex
stuff/main.go:23: undefined: groupShow
stuff/main.go:24: undefined: groupCreate
stuff/main.go:25: undefined: groupUpdate
stuff/main.go:26: undefined: groupDelete
我超級新去,但我想如果你把文件放在同一個軟件包中,那麼他們就可以訪問對方。我在這裏做錯了什麼?
感謝您的回答,但將group.go文件移到與main.go文件相同的目錄中仍會導致相同的錯誤。 – user1952811
您正在使用'go build'來構建應用程序,而不是運行,對吧?只要所有文件都是相同的包(在這種情況下是「package main」),它應該可以工作。 – elithrar
是的,這似乎是做的伎倆,感謝所有的幫助傢伙! – user1952811