gpt4 book ai didi

validation - gin-gonic 中的多部分文件上传验证

转载 作者:数据小太阳 更新时间:2023-10-29 03:32:02 27 4
gpt4 key购买 nike

我正在尝试为基于 GIN 框架的基于 go 的 Web 应用程序添加验证。在网页上,我正在选择一个文件并提交,服务器正在处理它。在服务器端,我尝试添加验证以检查文件是否已提供。如果没有,则重定向回原始页面。

    func panic(err error)  {
if err != nil {
log.Println(err)
}
}

func displayTable (c *gin.Context) {
file, _ , err := c.Request.FormFile("file")
panic(err)
if file == nil {
log.Println("File is nil.")
log.Println(err)
log.Println("*****")
c.HTML(http.StatusInternalServerError, "index.tmpl", gin.H{
"title": "Select the input file","error" : "Please select the input file.",
})
} else {
defer file.Close()
}
filename := strconv.FormatInt(time.Now().Unix(),10)
out, err := os.Create("./tmp/"+filename+".xml")
panic(err)
defer out.Close()
_, err = io.Copy(out, file)
panic(err)
xmlFile, err := os.Open("./tmp/"+filename+".xml")
panic(err)
defer xmlFile.Close()

// Other Implementation Details
}

即使在提供了处理之后,我仍然在 go 代码中感到 panic 。请让我知道我在实现中遗漏了什么。

谢谢。

    http: no such file
File is nil.
http: no such file
*****
2015/08/04 13:19:10 Panic recovery -> runtime error: invalid memory address or nil pointer dereference
c:/go/src/runtime/panic.go:387 (0x414d36)
c:/go/src/runtime/panic.go:42 (0x4142a5)
c:/go/src/runtime/os_windows.go:42 (0x414066)
c:/go/src/io/io.go:362 (0x45268f)
D:/code/src/exmp/serverexmaple.go:45 (0x40168f)
displayTable: _, err = io.Copy(out, file)
D:/code/src/github.com/gin-gonic/gin/context.go:95 (0x49f8ea)
(*Context).Next: c.handlers[c.index](c)
D:/code/src/github.com/gin-gonic/gin/logger.go:56 (0x4ac490)
func.007: c.Next()
D:/code/src/github.com/gin-gonic/gin/context.go:95 (0x49f8ea)
(*Context).Next: c.handlers[c.index](c)
D:/code/src/github.com/gin-gonic/gin/recovery.go:43 (0x4acc80)
func.009: c.Next()
D:/code/src/github.com/gin-gonic/gin/context.go:95 (0x49f8ea)
(*Context).Next: c.handlers[c.index](c)
D:/code/src/github.com/gin-gonic/gin/gin.go:292 (0x4a46d5)
(*Engine).handleHTTPRequest: context.Next()
D:/code/src/github.com/gin-gonic/gin/gin.go:273 (0x4a4459)
(*Engine).ServeHTTP: engine.handleHTTPRequest(c)
c:/go/src/net/http/server.go:1703 (0x468415)
c:/go/src/net/http/server.go:1204 (0x466408)
c:/go/src/runtime/asm_386.s:2287 (0x438ea1)

最佳答案

  1. 请不要重新定义panic。它会让所有了解 panic 工作原理的人感到困惑。
  2. 在 Go 中与 nil 进行比较有点棘手。它可能不像您预期​​的那样工作:Check for nil and nil interface in Go . FormFile 返回接口(interface),因此如果您想使用 nil 检查它或使用第二个参数(其类型可用),则必须将其转换为底层结构。
  3. 这不是特定于 GIN,它是 Go 的 HTTP 实现的一部分:http://golang.org/pkg/net/http/#Request.FormFile

关于validation - gin-gonic 中的多部分文件上传验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31800843/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com