我很新,想尝试学习,我正在设置一个带有 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/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何