登录
首页 >  Golang >  Go问答

Gin 框架中的 Golang:无法在 http 响应中正确返回数组

来源:stackoverflow

时间:2024-02-13 16:03:26 344浏览 收藏

本篇文章主要是结合我之前面试的各种经历和实战开发中遇到的问题解决经验整理的,希望这篇《Gin 框架中的 Golang:无法在 http 响应中正确返回数组》对你有很大帮助!欢迎收藏,分享给更多的需要的朋友学习~

问题内容

我正在尝试返回数组 []employee 作为响应。长度为 2。但是邮递员显示响应正文为空。

type people struct {
    height         int32          `json:"height" binding:"required"`
        weight         int32          `json:"weight" binding:"required"`
}

type employee struct {
    salary int `json:"salary"`
    people
}

c.json(http.statusok, employeearray)

我在google上发现golang有一些内部binding结构的问题。

upd:使用 marshaljson 覆盖的代码。这是问题所在

package main

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

type TypeName struct {
    Name string `json:"name" binding:"required"`
}

func (p TypeName) MarshalJSON() ([]byte, error) {
    return []byte("Joe"), nil
}

type People struct {
    Height int32 `json:"height" binding:"required"`
    Weight int32 `json:"weight" binding:"required"`
    TypeName
}

type Employee struct {
    Salary int `json:"salary"`
    People
}

func main() {
    r := gin.Default()

    r.GET("/employees", func(c *gin.Context) {
        employeeArray := []Employee{
            {
                Salary: 10000,
                People: People{
                    Height: 170,
                    Weight: 80,
                },
            },
            {
                Salary: 20000,
                People: People{
                    Height: 175,
                    Weight: 80,
                },
            },
        }

        c.JSON(http.StatusOK, employeeArray)
    })
    _ = r.Run()
}

正确答案


func (p typename) marshaljson() ([]byte, error) {
    return []byte("joe"), nil
}

[]byte("joe") 不是有效的 json。应该引用它。如果您注意 gin 的日志,您应该会看到一条错误消息: error #01: json: error calling marshaljson for type main.employee: invalid character 'j'looking for begin of value。这个应该可以工作:

func (p typename) marshaljson() ([]byte, error) {
    return []byte(`"joe"`), nil
}

这是 time.time 的演示:

package main

import (
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

type Time struct {
    StandardTime time.Time
}

func (p Time) MarshalJSON() ([]byte, error) {
    timeString := p.StandardTime.Format(time.RFC3339)
    return json.Marshal(timeString)
}

func main() {
    r := gin.Default()

    r.GET("/time", func(c *gin.Context) {
        timeArray := []Time{
            {
                StandardTime: time.Now(),
            },
            {
                StandardTime: time.Now().Add(30 * time.Minute),
            },
        }

        c.JSON(http.StatusOK, timeArray)
    })
    _ = r.Run()
}

到这里,我们也就讲完了《Gin 框架中的 Golang:无法在 http 响应中正确返回数组》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>