duan205571 2019-04-13 04:11
浏览 31
已采纳

如何导入路线

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

  • 写回答

1条回答 默认 最新

  • dongzh1988 2019-04-13 08:12
    关注

    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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效