- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我很新,想尝试学习,我正在设置一个带有 gin-gonic 服务器的应用程序。我设法让它与主包中的所有内容一起工作,我想更好地组织它与包中所有最相关的(我管理的)并按文件拆分每个组 CRUD。
所以在 init 函数中包的“主”文件中,我定义了:
Router := gin.New()
Router.Use(gin.Logger())
Router.Use(gin.Recovery())
虽然我可以在包的其他文件中像那样使用它:
v1 := Router.Group("/api/v1/todos")
v1.Use(AuthRequired())
{
v1.POST("/", CreateTodo)
v1.GET("/", FetchAllTodo)
v1.GET("/:id", FetchSingleTodo)
v1.PUT("/:id", UpdateTodo)
v1.DELETE("/:id", DeleteTodo)
}
或
packagename.Router.Group
但没有一个在工作,我得到:
undefined: Router in Router.Group
斯蒂芬PS:我确实为包设置了一个子文件夹,如果它在一个文件中,我可以构建它。
虽然解决方案是将 Router 变量声明为 *gin.Engine,但是当它编译正常时,我在 Router.Group 调用中遇到了紧急错误
让我贴出更多的代码:
主代码.go :
package main
import (
"fmt"
"./apirest"
"github.com/braintree/manners"
)
func main(){
fmt.Printf("hello world.\n")
//router.Run()
manners.ListenAndServe(":8080", apirest.Router)
}
然后我将 apirest 包分成 2 个文件:
apirest.go(我做了手动清理,也许我错过了导入):
package apirest
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/braintree/manners"
"os"
"os/signal"
)
//Router pour gérer l'api
var Router *gin.Engine
/*
MAIN FUNCTION
*/
func init() {
Router := gin.New()
Router.Use(gin.Logger())
Router.Use(gin.Recovery())
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func(){
for sig := range c {
// sig is a ^C, handle it
fmt.Printf("ctl+c catched "+sig.String())
manners.Close()
}
}()
LoadMonitor()
}
然后是处理所有声明的 todoCRUD.go 文件,todoCRUD.go 和 apirest.go 在同一个子文件夹 apirest 中(并且编译正常):
package apirest
import (
"fmt"
"github.com/gin-gonic/gin"
"gopkg.in/validator.v2"
"github.com/jinzhu/gorm"
"strconv"
"net/http"
"time"
)
//Todo definition d'un element todo
type Todo struct {
gorm.Model
CreatedAt time.Time
UpdatedAt time.Time
OwnerID int `json:"ownerid" validate:"nonzero"`
URL string `json:"url"`
}
//TransformedTodo version pour le retour d'api sans certaines infos
type TransformedTodo struct {
ID uint `json:"id"`
CreatedAt time.Time
UpdatedAt time.Time
OwnerID uint `json:"ownerid"`
URL string `json:"url"`
}
//LoadTodo permet de lancer le mappage todos
func LoadTodo(){
v1 := Router.Group("/api/v1/todos")
{
v1.POST("/", CreateTodo)
v1.GET("/", FetchAllTodo)
v1.GET("/:id", FetchSingleTodo)
v1.PUT("/:id", UpdateTodo)
v1.DELETE("/:id", DeleteTodo)
}
}
//CreateTodo génération d'un todo
func CreateTodo(c *gin.Context) {
owner, _ := strconv.Atoi(c.PostForm("ownerid"))
todo := Todo{
OwnerID: owner,
URL: c.PostForm("url"),
};
v := validator.NewValidator()
if errs := v.Validate(todo); errs!=nil {
errors := errs.(validator.ErrorMap)
var errOuts []string
for f, e := range errors {
errOuts = append(errOuts, fmt.Sprintf("\t - %s (%v)\n", f, e))
}
//c.JSON(500, gin.H{"Error": errs.Error()})
c.JSON(500, gin.H{"Erreur sur le(s) champ(s) : ": errOuts})
} else {
db, _ := Database()
defer db.Close()
db.Save(&todo)
c.JSON(http.StatusCreated, gin.H{"status" : http.StatusCreated, "message" : "Todo item created successfully!", "resourceId": todo.ID})
}
}
//FetchAllTodo récupération de tous les todos
func FetchAllTodo(c *gin.Context) {
var todos []Todo
var _todos []TransformedTodo
db, _ := Database()
defer db.Close()
db.Find(&todos)
if (len(todos) <= 0) {
c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
return
}
//transforms the todos for building a good response,
//je peux choisir des champs a ne pas display
for _, item := range todos {
status := false
if (item.Status == 1) {
status = true
} else {
status = false
}
_todos = append(_todos, TransformedTodo{ID: item.ID, URL:item.URL})
}
c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "data" : _todos})
}
//FetchSingleTodo Récupération d'un seul todo en fonction de son id
func FetchSingleTodo(c *gin.Context) {
var todo Todo
todoID := c.Param("id")
db, _ := Database()
defer db.Close()
db.First(&todo, todoID)
if (todo.ID == 0) {
c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
return
}
_todo := TransformedTodo{ID: todo.ID, URL:todo.URL}
c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "data" : _todo})
}
//UpdateTodo Mise à jour d'un todo
func UpdateTodo(c *gin.Context) {
var todo Todo
todoID := c.Param("id")
db, _ := Database()
defer db.Close()
db.First(&todo, todoID)
if (todo.ID == 0) {
c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
return
}
db.Model(&todo).Update("title", c.PostForm("title"))
db.Model(&todo).Update("completed", c.PostForm("completed"))
c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "message" : "Todo updated successfully!"})
}
//DeleteTodo Suppression d'un todo
func DeleteTodo(c *gin.Context) {
var todo Todo
todoID := c.Param("id")
db, _ := Database()
defer db.Close()
db.First(&todo, todoID)
if (todo.ID == 0) {
c.JSON(http.StatusNotFound, gin.H{"status" : http.StatusNotFound, "message" : "No todo found!"})
return
}
db.Delete(&todo)
c.JSON(http.StatusOK, gin.H{"status" : http.StatusOK, "message" : "Todo deleted successfully!"})
}
想法是让每个实体都有一个 xxxxCRUD.go 文件来处理,但整个文件夹在同一个包中。
确切的错误是:
PS D:\www\developpement> go run .\maincode.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)
panic: runtime error: invalid memory address or nil pointer dereference [signal 0xc0000005 code=0x0 addr=0x0 pc=0x46cc0f]
goroutine 1 [running]: panic(0x831880, 0xc04200a080) C:/Go/src/runtime/panic.go:500 +0x1af /D/www/developpement/apirest.LoadTodo() D:/www/developpement/apirest/todoCRUD.go:33 +0x2f [Router.Group] /D/www/developpement/apirest.init.1() D:/www/developpement/apirest/apirest.go:73 +0x220 [LoadTodo()] /D/www/developpement/apirest.init() D:/www/developpement/apirest/todoCRUD.go:190 +0x80 [last line] main.init() D:/www/developpement/maincode.go:13 +0x3a [manners.ListenAndServe(":8080", apirest.Router)] exit status 2
我希望这有助于理解!
感谢您的宝贵时间和帮助!
斯蒂芬
最佳答案
我确实设法通过在 LoadTodo 函数中“发送”路由器使其工作:
在 apirest.go 中:
LoadTodo(Router)
在 todoCRUD.go 中:
func LoadTodo(r *gin.Engine){
它工作正常......我希望我没有在代码中带来错误故障......
斯蒂芬
关于rest - golang gin-gonic 和包中的拆分文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42209040/
我想做的是让 JTextPane 在 JPanel 中占用尽可能多的空间。对于我使用的 UpdateInfoPanel: public class UpdateInfoPanel extends JP
我在 JPanel 中有一个 JTextArea,我想将其与 JScrollPane 一起使用。我正在使用 GridBagLayout。当我运行它时,框架似乎为 JScrollPane 腾出了空间,但
我想在 xcode 中实现以下功能。 我有一个 View Controller 。在这个 UIViewController 中,我有一个 UITabBar。它们下面是一个 UIView。将 UITab
有谁知道Firebird 2.5有没有类似于SQL中“STUFF”函数的功能? 我有一个包含父用户记录的表,另一个表包含与父相关的子用户记录。我希望能够提取用户拥有的“ROLES”的逗号分隔字符串,而
我想使用 JSON 作为 mirth channel 的输入和输出,例如详细信息保存在数据库中或创建 HL7 消息。 简而言之,输入为 JSON 解析它并输出为任何格式。 最佳答案 var objec
通常我会使用 R 并执行 merge.by,但这个文件似乎太大了,部门中的任何一台计算机都无法处理它! (任何从事遗传学工作的人的附加信息)本质上,插补似乎删除了 snp ID 的 rs 数字,我只剩
我有一个以前可能被问过的问题,但我很难找到正确的描述。我希望有人能帮助我。 在下面的代码中,我设置了varprice,我想添加javascript变量accu_id以通过rails在我的数据库中查找记
我有一个简单的 SVG 文件,在 Firefox 中可以正常查看 - 它的一些包装文本使用 foreignObject 包含一些 HTML - 文本包装在 div 中:
所以我正在为学校编写一个 Ruby 程序,如果某个值是 1 或 3,则将 bool 值更改为 true,如果是 0 或 2,则更改为 false。由于我有 Java 背景,所以我认为这段代码应该有效:
我做了什么: 我在这些账户之间创建了 VPC 对等连接 互联网网关也连接到每个 VPC 还配置了路由表(以允许来自双方的流量) 情况1: 当这两个 VPC 在同一个账户中时,我成功测试了从另一个 La
我有一个名为 contacts 的表: user_id contact_id 10294 10295 10294 10293 10293 10294 102
我正在使用 Magento 中的新模板。为避免重复代码,我想为每个产品预览使用相同的子模板。 特别是我做了这样一个展示: $products = Mage::getModel('catalog/pro
“for”是否总是检查协议(protocol)中定义的每个函数中第一个参数的类型? 编辑(改写): 当协议(protocol)方法只有一个参数时,根据该单个参数的类型(直接或任意)找到实现。当协议(p
我想从我的 PHP 代码中调用 JavaScript 函数。我通过使用以下方法实现了这一点: echo ' drawChart($id); '; 这工作正常,但我想从我的 PHP 代码中获取数据,我使
这个问题已经有答案了: Event binding on dynamically created elements? (23 个回答) 已关闭 5 年前。 我有一个动态表单,我想在其中附加一些其他 h
我正在尝试找到一种解决方案,以在 componentDidMount 中的映射项上使用 setState。 我正在使用 GraphQL连同 Gatsby返回许多 data 项目,但要求在特定的 pat
我在 ScrollView 中有一个 View 。只要用户按住该 View ,我想每 80 毫秒调用一次方法。这是我已经实现的: final Runnable vibrate = new Runnab
我用 jni 开发了一个 android 应用程序。我在 GetStringUTFChars 的 dvmDecodeIndirectRef 中得到了一个 dvmabort。我只中止了一次。 为什么会这
当我到达我的 Activity 时,我调用 FragmentPagerAdapter 来处理我的不同选项卡。在我的一个选项卡中,我想显示一个 RecyclerView,但他从未出现过,有了断点,我看到
当我按下 Activity 中的按钮时,会弹出一个 DialogFragment。在对话框 fragment 中,有一个看起来像普通 ListView 的 RecyclerView。 我想要的行为是当
我是一名优秀的程序员,十分优秀!