2015-06-27 100 views
-2

我有兩個文件main.gogroup.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") 
} 

所以方法groupIndexgroupCreategroupUpdate等位於另一個文件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 

我超級新去,但我想如果你把文件放在同一個軟件包中,那麼他們就可以訪問對方。我在這裏做錯了什麼?

回答

2

有兩種方法來解決這個問題:

  1. 移動group.go到同一目錄main.go.
  2. 將group.go作爲包導入。在group.go更改包聲明:

    包路線//或您選擇

出口用一個大寫字母開始他們的功能名稱:

func GroupIndex(c *gin.Context) { 

進口從主包:

import "path/to/routes" 
... 
groups.GET("/", routes.GroupIndex) 

該文件How To Write Go Code解釋了這一點d更多。

+0

感謝您的回答,但將group.go文件移到與main.go文件相同的目錄中仍會導致相同的錯誤。 – user1952811

+2

您正在使用'go build'來構建應用程序,而不是運行,對吧?只要所有文件都是相同的包(在這種情況下是「package main」),它應該可以工作。 – elithrar

+0

是的,這似乎是做的伎倆,感謝所有的幫助傢伙! – user1952811