如何导入路线

I just started a Go project by following the tutorial on Pluralsight, but I experienced a bit of an obstacle when I wanted to separate all of my routes into one file route.

Previously my code went well:

main.go

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func main() {
    r := gin.Default()
    r.LoadHTMLGlob("templates/*.html")

    r.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Helo from %v", "Gin")
    })

    r.GET("/json", func(c *gin.Context) {
        c.JSON(200, gin.H {
            "status":  "posted",
            "message": "Hi...",
            "nick":    "Nick here",
        })
    })

    r.GET("/template/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })

    r.Run(":3000")
}

Until here, all of my code is running well.

Then I made a route file like this:

routes.go

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

func registerRoutes() *gin.Engine {
    r := gin.Default()
    r.LoadHTMLGlob("templates/*.html")

    r.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "Helo from %v", "Gin")
    })

    r.GET("/json", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "status":  "posted",
            "message": "Hi broh",
            "nick":    "Nick here",
        })
    })

    r.GET("/template/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", nil)
    })

    return r
}

And I changed the code on my main.go to:

package main

func main() {
    r := registerRoutes()

    r.Run(":3000")
}

When I run it, I get an error:

go build main.go
# command-line-arguments
.\main.go:4:7: undefined: registerRoutes

I have tried to understand it but I always get that error message. Is something wrong with my code?

My project structure:

enter image description here

You need both things:

  • Run your application with go run ./... or go run main.go model.go routes.go
  • Rename your function registerRoutes to RegisterRoutes, to make your function public, and visible in your package