搜尋
首頁後端開發GolangGolang gin接收json資料和影像

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 解析表單欄位值。請參閱 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 literal
  2. c.formfile("avatar") 之後呼叫c.bindjson 不起作用,因為呼叫c.formfile 會使整個請求正文被讀取。而 c.bindjson 後面也沒有什麼可讀的。這就是您看到 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中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
C和Golang:表演至關重要時C和Golang:表演至關重要時Apr 13, 2025 am 12:11 AM

C 更適合需要直接控制硬件資源和高性能優化的場景,而Golang更適合需要快速開發和高並發處理的場景。 1.C 的優勢在於其接近硬件的特性和高度的優化能力,適合遊戲開發等高性能需求。 2.Golang的優勢在於其簡潔的語法和天然的並發支持,適合高並發服務開發。

Golang行動:現實世界中的示例和應用程序Golang行動:現實世界中的示例和應用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go編程語言解釋了Golang:Go編程語言解釋了Apr 10, 2025 am 11:18 AM

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Golang的目的:建立高效且可擴展的系統Golang的目的:建立高效且可擴展的系統Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

SQL排序中ORDER BY語句結果為何有時看似隨機?SQL排序中ORDER BY語句結果為何有時看似隨機?Apr 02, 2025 pm 05:24 PM

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

技術棧收斂是否僅僅是技術棧選型的過程?技術棧收斂是否僅僅是技術棧選型的過程?Apr 02, 2025 pm 05:21 PM

技術棧收斂與技術選型的關係在軟件開發中,技術棧的選擇和管理是一個非常關鍵的問題。最近,有讀者提出了...

如何在Go語言中使用反射對比並處理三個結構體的差異?如何在Go語言中使用反射對比並處理三個結構體的差異?Apr 02, 2025 pm 05:15 PM

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

See all articles

熱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尊渡假赌尊渡假赌尊渡假赌

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器