目录
问题内容
解决方法
tl;dr
gin可以自动解析multipart/form-data中的其他内容类型吗?
首页 后端开发 Golang Golang gin接收json数据和图像

Golang gin接收json数据和图像

Feb 09, 2024 pm 01:09 PM

Golang gin接收json数据和图像

php小编百草为您介绍Golang gin框架中如何接收JSON数据和图像。在开发过程中,我们经常需要处理前端传递过来的JSON数据以及图像文件。Golang的gin框架提供了简单易用的方法来接收和处理这些数据。通过本文的介绍,您将了解到如何在gin框架中使用结构体来接收JSON数据,以及如何处理上传的图像文件。让我们一起来探索吧!

问题内容

我有请求处理程序的代码:

func (h *handlers) updateprofile() gin.handlerfunc {
    type request struct {
        username    string `json:"username" binding:"required,min=4,max=20"`
        description string `json:"description" binding:"required,max=100"`
    }

    return func(c *gin.context) {
        var updaterequest request

        if err := c.bindjson(&updaterequest); err != nil {
            var validationerrors validator.validationerrors

            if errors.as(err, &validationerrors) {
                validateerrors := base.bindingerror(validationerrors)
                c.abortwithstatusjson(http.statusbadrequest, gin.h{"error": validateerrors})
            } else {
                c.abortwitherror(http.statusbadrequest, err)
            }

            return
        }

        avatar, err := c.formfile("avatar")
        if err != nil {
            c.abortwithstatusjson(http.statusbadrequest, gin.h{
                "error": "image not contains in request",
            })
            return
        }

        log.print(avatar)

        if avatar.size > 3<<20 { // if avatar size more than 3mb
            c.abortwithstatusjson(http.statusbadrequest, gin.h{
                "error": "image is too large",
            })
            return
        }

        file, err := avatar.open()
        if err != nil {
            c.abortwitherror(http.statusinternalservererror, err)
        }

        session := sessions.default(c)
        id := session.get("sessionid")
        log.printf("id type: %t", id)

        err = h.userservice.updateprofile(fmt.sprintf("%v", id), file, updaterequest.username, updaterequest.description)
        if err != nil {
            c.abortwithstatusjson(http.statusbadrequest, gin.h{})
            return
        }

        c.indentedjson(http.statusnocontent, gin.h{"message": "succesfull update"})
    }
}
登录后复制

我对此处理程序进行了单元测试:

func testuser_updateprofile(t *testing.t) {
    type testcase struct {
        name               string
        image              io.reader
        username           string
        description        string
        expectedstatuscode int
    }

    router := gin.default()

    memstore := memstore.newstore([]byte("secret"))
    router.use(sessions.sessions("session", memstore))

    usergroup := router.group("user")
    repo := user.newmemory()
    service := userservice.new(repo)
    userhandlers.register(usergroup, service)

    testimage := make([]byte, 100)
    rand.read(testimage)
    image := bytes.newreader(testimage)

    testcases := []testcase{
        {
            name:               "request with image",
            image:              image,
            username:           "bobik",
            description:        "wanna be sharik",
            expectedstatuscode: http.statusnocontent,
        },
        {
            name:               "request without image",
            image:              nil,
            username:           "sharik",
            description:        "wanna be bobik",
            expectedstatuscode: http.statusnocontent,
        },
    }

    for _, tc := range testcases {
        t.run(tc.name, func(t *testing.t) {
            body := &bytes.buffer{}
            writer := multipart.newwriter(body)

            imagewriter, err := writer.createformfile("avatar", "test_avatar.jpg")
            if err != nil {
                t.fatal(err)
            }

            if _, err := io.copy(imagewriter, image); err != nil {
                t.fatal(err)
            }

            data := map[string]interface{}{
                "username":    tc.username,
                "description": tc.description,
            }
            jsondata, err := json.marshal(data)
            if err != nil {
                t.fatal(err)
            }

            jsonwriter, err := writer.createformfield("json")
            if err != nil {
                t.fatal(err)
            }

            if _, err := jsonwriter.write(jsondata); err != nil {
                t.fatal(err)
            }

            writer.close()

            // creating request
            req := httptest.newrequest(
                http.methodpost,
                "http://localhost:8080/user/account/updateprofile",
                body,
            )
            req.header.set("content-type", writer.formdatacontenttype())
            log.print(req)

            w := httptest.newrecorder()
            router.servehttp(w, req)

            assert.equal(t, tc.expectedstatuscode, w.result().statuscode)
        })
    }
}
登录后复制

在测试过程中出现以下错误: 错误#01:数字文字中的无效字符“-”

这是请求正文(我用 log.print(req) 打印它):

&{POST http://localhost:8080/user/account/updateprofile HTTP/1.1 1 1 map[Content-Type:[multipart/form-data; boundary=30b24345de9d8d83ecbdd146262d86894c45b4f3485e4615553621fd2035]] {--30b24345de9d8d83ecbdd146262d86894c45b4f3485e4615553621fd2035
Content-Disposition: form-data; name="avatar"; filename="test_avatar.jpg"
Content-Type: application/octet-stream


--30b24345de9d8d83ecbdd146262d86894c45b4f3485e4615553621fd2035
Content-Disposition: form-data; name="json"

{"description":"wanna be bobik","username":"sharik"}
--30b24345de9d8d83ecbdd146262d86894c45b4f3485e4615553621fd2035--
} <nil> 414 [] false localhost:8080 map[] map[] <nil> map[] 192.0.2.1:1234 http://localhost:8080/user/account/updateprofile <nil> <nil> <nil> <nil>}
登录后复制

首先,我只有字符串作为 json 数据并将其转换为字节。当出现错误时,我使用 json.marshal 转换了 json 数据,但没有成功。我想用 c.bind 解析 json 数据并用 c.formfile 解析给定图像,这可能吗?

更新。我替换了代码先获取头像,然后通过bind结构获取json。现在我有 eof 错误。

解决方法

tl;dr

我们可以定义一个结构体来同时接收json数据和图像文件(注意字段标签):

var updaterequest struct {
    avatar *multipart.fileheader `form:"avatar" binding:"required"`
    user   struct {
        username    string `json:"username" binding:"required,min=4,max=20"`
        description string `json:"description" binding:"required,max=100"`
    } `form:"user" binding:"required"`
}

// c.shouldbind will choose binding.formmultipart based on the content-type header.
// we call c.shouldbindwith to make it explicitly.
if err := c.shouldbindwith(&updaterequest, binding.formmultipart); err != nil {
    _ = c.abortwitherror(http.statusbadrequest, err)
    return
}
登录后复制

gin可以自动解析multipart/form-data中的其他内容类型吗?

例如,xmlyaml

当前的 gin (@1.9.0) 不会自动解析 multipart/form-data 中的 xmlyamljson 很幸运,因为当目标字段是结构体或映射时,gin 恰好使用 json.unmarshal 中的 json 很幸运,因为当目标字段是结构体或映射时,gin 恰好使用 json.unmarshal 解析表单字段值。请参阅 binding.setwithpropertype

updaterequest.event我们可以像这样自己解析它们(

是表单中的字符串值):

var event struct {
    at     time.time `xml:"time" binding:"required"`
    player string    `xml:"player" binding:"required"`
    action string    `xml:"action" binding:"required"`
}

if err := binding.xml.bindbody([]byte(updaterequest.event), &event); err != nil {
    _ = c.abortwitherror(http.statusbadrequest, err)
    return
}
登录后复制
application/xml 请求中的 yamlapplication/x-yaml 请求中的 xml 混淆。仅当 xml 内容或 yaml 内容位于 中时才需要这样做多部分/表单-data(请不要与

请求) .

其他
  1. c.bindjson 不能用于从 multipart/form-data 读取 json,因为它假定请求正文以有效的 json 开头。但它是从一个边界开始的,看起来像 --30b24345d...。这就是为什么它失败并显示错误消息 invalid character '-' in numeric literalc.bindjson 不能用于从
  2. 读取 json,因为它假定请求正文以有效的 json 开头。但它是从一个边界开始的,看起来像 --30b24345d...。这就是为什么它失败并显示错误消息 invalid character '-' in numeric literal
  3. c.formfile("avatar") 之后调用 c.bindjson 不起作用,因为调用 c.formfile 会使整个请求正文被读取。并且 c.bindjson
  4. 后面没有什么可读的。这就是您看到 eof 错误的原因。

单个可运行文件中的演示

go test 运行 ./... -v -count 1这是完整的演示。使用

:

package m

import (
    "bytes"
    "crypto/rand"
    "fmt"
    "io"
    "mime/multipart"
    "net/http"
    "net/http/httptest"
    "testing"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"
    "github.com/stretchr/testify/assert"
)

func handle(c *gin.Context) {
    var updateRequest struct {
        Avatar *multipart.FileHeader `form:"avatar" binding:"required"`
        User   struct {
            Username    string `json:"username" binding:"required,min=4,max=20"`
            Description string `json:"description" binding:"required,max=100"`
        } `form:"user" binding:"required"`
        Event string `form:"event" binding:"required"`
    }

    // c.ShouldBind will choose binding.FormMultipart based on the Content-Type header.
    // We call c.ShouldBindWith to make it explicitly.
    if err := c.ShouldBindWith(&updateRequest, binding.FormMultipart); err != nil {
        _ = c.AbortWithError(http.StatusBadRequest, err)
        return
    }
    fmt.Printf("%#v\n", updateRequest)

    var event struct {
        At     time.Time `xml:"time" binding:"required"`
        Player string    `xml:"player" binding:"required"`
        Action string    `xml:"action" binding:"required"`
    }

    if err := binding.XML.BindBody([]byte(updateRequest.Event), &event); err != nil {
        _ = c.AbortWithError(http.StatusBadRequest, err)
        return
    }

    fmt.Printf("%#v\n", event)
}

func TestMultipartForm(t *testing.T) {
    testImage := make([]byte, 100)

    if _, err := rand.Read(testImage); err != nil {
        t.Fatal(err)
    }
    image := bytes.NewReader(testImage)

    body := &bytes.Buffer{}
    writer := multipart.NewWriter(body)

    imageWriter, err := writer.CreateFormFile("avatar", "test_avatar.jpg")
    if err != nil {
        t.Fatal(err)
    }

    if _, err := io.Copy(imageWriter, image); err != nil {
        t.Fatal(err)
    }

    if err := writer.WriteField("user", `{"username":"bobik","description":"wanna be sharik"}`); err != nil {
        t.Fatal(err)
    }

    xmlBody := `<?xml version="1.0" encoding="UTF-8"?>
<root>
   <time>2023-02-14T19:04:12Z</time>
   <player>playerOne</player>
   <action>strike (miss)</action>
</root>`
    if err := writer.WriteField("event", xmlBody); err != nil {
        t.Fatal(err)
    }

    writer.Close()

    req := httptest.NewRequest(
        http.MethodPost,
        "http://localhost:8080/update",
        body,
    )
    req.Header.Set("Content-Type", writer.FormDataContentType())
    fmt.Printf("%v\n", req)

    w := httptest.NewRecorder()
    c, engine := gin.CreateTestContext(w)
    engine.POST("/update", handle)
    c.Request = req
    engine.HandleContext(c)

    assert.Equal(t, 200, w.Result().StatusCode)
}
登录后复制
感谢您的阅读!🎜

以上是Golang gin接收json数据和图像的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作为广泛应用于安全通信的开源库,提供了加密算法、密钥和证书管理等功能。然而,其历史版本中存在一些已知安全漏洞,其中一些危害极大。本文将重点介绍Debian系统中OpenSSL的常见漏洞及应对措施。DebianOpenSSL已知漏洞:OpenSSL曾出现过多个严重漏洞,例如:心脏出血漏洞(CVE-2014-0160):该漏洞影响OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻击者可利用此漏洞未经授权读取服务器上的敏感信息,包括加密密钥等。

您如何使用PPROF工具分析GO性能? 您如何使用PPROF工具分析GO性能? Mar 21, 2025 pm 06:37 PM

本文解释了如何使用PPROF工具来分析GO性能,包括启用分析,收集数据并识别CPU和内存问题等常见的瓶颈。

您如何在GO中编写单元测试? 您如何在GO中编写单元测试? Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

Go语言中用于浮点数运算的库有哪些? Go语言中用于浮点数运算的库有哪些? Apr 02, 2025 pm 02:06 PM

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go的爬虫Colly中Queue线程的问题是什么? Go的爬虫Colly中Queue线程的问题是什么? Apr 02, 2025 pm 02:09 PM

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

从前端转型后端开发,学习Java还是Golang更有前景? 从前端转型后端开发,学习Java还是Golang更有前景? Apr 02, 2025 am 09:12 AM

后端学习路径:从前端转型到后端的探索之旅作为一名从前端开发转型的后端初学者,你已经有了nodejs的基础,...

您如何在go.mod文件中指定依赖项? 您如何在go.mod文件中指定依赖项? Mar 27, 2025 pm 07:14 PM

本文讨论了通过go.mod,涵盖规范,更新和冲突解决方案管理GO模块依赖关系。它强调了最佳实践,例如语义版本控制和定期更新。

您如何在GO中使用表驱动测试? 您如何在GO中使用表驱动测试? Mar 21, 2025 pm 06:35 PM

本文讨论了GO中使用表驱动的测试,该方法使用测试用例表来测试具有多个输入和结果的功能。它突出了诸如提高的可读性,降低重复,可伸缩性,一致性和A

See all articles