duanlongling5308 2015-06-27 21:30 采纳率: 0%
浏览 96
已采纳

将Go代码拆分到多个文件时遇到问题

I have two files main.go and group.go... it looks something like this

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")
}

So the methods groupIndex, groupCreate, groupUpdate, etc are located in another file under 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'}")
}

But when I try to compile I get the following error

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

I'm super new to go, but I thought if you put files in the same package, then they'll have access to each other. What am I doing wrong here?

  • 写回答

1条回答 默认 最新

  • duan0821 2015-06-27 21:40
    关注

    There are two ways to fix this:

    1. Move group.go to the same directory as main.go.
    2. Import group.go as a package. Change the package declaration on group.go to:

      package routes // or the name of your choice

    Export the functions by starting them with a capital letter:

    func GroupIndex(c *gin.Context) {
    

    Import the package from main:

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

    The document How To Write Go Code explains this and more.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog