遇到问题分裂代码走在多个文件中

问题描述:

我有两个文件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 

我超级新去,但我想如果你把文件放在同一个软件包中,那么他们就可以访问对方。我在这里做错了什么?

有两种方法来解决这个问题:

  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