尝试提供Gin Gonic应用程序时出现紧急错误

时间:2016-11-26 00:21:46

标签: go

我正在尝试使用Gin framework for Go创建一个小API,并且在尝试将其拆分为多个文件时遇到错误。由于我是Go的绝对初学者,我可能会犯一些大愚蠢的错误,所以请耐心等待我:) 我的项目结构如下:

project structure

models.go

.container {
  display: block;
  position: absolute;
  width: 50%;
  height: 50%;
}

.inner-container {
  display: block;
  overflow-y: scroll;
  overflow-x: hidden;

  background-color: yellow;
  position: relative;
  z-index: 10;
  width: 100%;
  height: 100%;
}

#element1 {
  background-color: red;
  padding: 1em;
}
#element2 {
  background-color: green;
  padding: 1em;
}
#element3 {
  background-color: blue;
  position: absolute;
  right: -2em;
  bottom: -2em;
  height: 4em;
  width: 4em;
  z-index: 20;
}

url_mappings.go

package models

type Note struct {
    Title   string `form:"title" json:"title" binding:"required"`
    Body    string `form:"body" json:"body" binding:"required"`
}

var Notes []Note

func MockData() {
    Notes = append(Notes, Note{Title: "My first note", Body: "Brazil beated Argentina very badly :("})
    Notes = append(Notes, Note{Title: "Some more notes", Body: "I hope we can defeat Colombia"})
}

main.go

package mappings

import (
    "gopkg.in/gin-gonic/gin.v1"
    "github.com/juanmougan/notepad/api/controllers"
)

var Router *gin.Engine

func CreateUrlMappings() {
    Router := gin.Default()
    // v1 of the API
    v1 := Router.Group("/v1")
    {
        v1.GET("/notes", controllers.AllNotesEndpoint)
    }
}

notes_controllers.go

package main

import (
    "github.com/juanmougan/notepad/api/models"
    "github.com/juanmougan/notepad/api/mappings"
)

func main() {
    // TODO eventually use a real DB
    models.MockData()
    mappings.CreateUrlMappings()
    // Listen and server on 0.0.0.0:8080
    mappings.Router.Run(":8080")
}

当我运行应用程序时,似乎启动确定

package controllers

import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
    "github.com/juanmougan/notepad/api/models"
)

func AllNotesEndpoint(c *gin.Context) {
    c.JSON(http.StatusOK, models.Notes)
}

但是在尝试导航到MacBook-Pro-de-Juan:notepad juanma$ go run api/main/main.go [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET /v1/notes --> github.com/juanmougan/notepad/api/controllers.AllNotesEndpoint (3 handlers) [GIN-debug] Listening and serving HTTP on :8080 时,我收到了此错误:

http://localhost:8080/v1/notes

这很奇怪,因为我没有看到任何对我自己的代码的引用。我发现了一些类似的问题like this,但是所有这些问题似乎都在堆栈跟踪顶部的代码上有错误。我可以看到,我只是出现了框架错误 关于这里可能出现什么问题的任何想法?

提前致谢

1 个答案:

答案 0 :(得分:1)

更改映射的初始化

var Router *gin.Engine

func CreateUrlMappings() {
    Router = gin.Default()
    // v1 of the API
    v1 := Router.Group("/v1")
    {
        v1.GET("/notes", controllers.AllNotesEndpoint)
    }
}

当您使用":="时,您正在创建新的本地变量操作

Router := gin.Default()  // this is wrong if you are using a global var