将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?

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.