How do I return a struct as json using fiber in golang?

huangapple go评论78阅读模式
英文:

How do I return a struct as json using fiber in golang?

问题

由于我在互联网上找不到关于这个简单问题的教程,所以我必须在这里写下来寻求帮助。

我有这个函数:

package main

import (
	"encoding/json"

	"github.com/gofiber/fiber/v2"
)

type Person struct {
	email string
}

func main() {
	app := fiber.New()

	app.Get("/", func(c *fiber.Ctx) error {
		user := Person{
			email: "mikolaj73@gmail.com",
		}

		u, err := json.Marshal(user)

		if err != nil {
			panic(err)
		}

		return c.JSON(u)
	})

	app.Listen(":5000")
}

但是当我访问 127.0.0.1:5000 时,它显示的是 "e30=" 而不是用户的 JSON。我该怎么做?

英文:

Since I couldn't find any tutorial on internet about this simple problem, I must write here to get help.

I have this function:

package main

import (
	"encoding/json"

	"github.com/gofiber/fiber/v2"
)


type Person struct {
	email string
}

func main() {
	app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
		user := Person{
			email: "mikolaj73@gmail.com",
		}

		u, err := json.Marshal(user);

		if err != nil {
            panic(err)
        }

        return c.JSON(u);
    })

    app.Listen(":5000")
}

But when I visit 127.0.0.1:5000, it says: "e30=" instead of the user json. How do I do it?

答案1

得分: 1

请注意,我将为您翻译以下代码片段:

看到这个
> type Person struct {
    Email string
}

你的结构体成员必须大写然后json.Marshal才能正常工作


> return c.JSON(u)

改为

> return c.SendString(string(u))

如果使用c.JSON它会将您的字符串转换为Base64格式

    package main

    import (
        "encoding/json"

        "github.com/gofiber/fiber/v2"
	    "fmt"
    )


    type Person struct {
        Email string
    }

    func main() {
        app := fiber.New()
    
        app.Get("/", func(c *fiber.Ctx) error {
            user := Person{
                Email: "mikolaj73@gmail.com",
            }
		    fmt.Println(user)
            u, err := json.Marshal(user);

            if err != nil {
                panic(err)
            }
		    fmt.Println(u)
		    fmt.Println(string(u))
		    return c.SendString(string(u))
        })

        app.Listen(":5000")
    }

在完成整个项目之前始终使用Println或其他方法进行调试

请注意,我已经将代码中的HTML实体编码(>)转换为正常的字符。希望这可以帮助到您!

英文:

See this
> type Person struct {
Email string
}

Your member of struct must be uppercase,then json.Marshal will work

Change
> return c.JSON(u)

To

> return c.SendString(string(u))

If Using c.JSON It Will Turn Your String Be Base64 format

package main

import (
    "encoding/json"

    "github.com/gofiber/fiber/v2"
    "fmt"
)


type Person struct {
    Email string
}

func main() {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        user := Person{
            Email: "mikolaj73@gmail.com",
        }
	    fmt.Println(user)
        u, err := json.Marshal(user);

        if err != nil {
            panic(err)
        }
	    fmt.Println(u)
	    fmt.Println(string(u))
	    return c.SendString(string(u))
    })

    app.Listen(":5000")
}

Always Using Println Or Something To Debug Before Complete Full Project

答案2

得分: 1

如其他人所分享的,fiber.Ctx.JSON会自动进行编组。在之前调用json.Marshall意味着你进行了两次编组。只需删除这一部分。

实际上,在这里你需要使用c.JSON。不要手动编组并返回字符串。

fiber.Ctx.SendString的响应头部不正确,为“Content-Type: text/plain”,而fiber.Ctx.JSON的响应头部正确为“Content-Type: application/json”(在两种情况下都是预期的行为)。

英文:

As others have shared, fiber.Ctx.JSON does the marshaling for you. Calling json.Marshall beforehand means you are marshaling twice. Just drop that off.

You actually need to use c.JSON here. Do not manually marshal and return as string.

fiber.Ctx.SendString responds incorrectly with header "Content-Type: text/plain" while fiber.Ctx.JSON responds correctly with "Content-Type: application/json" (expected behavior in both cases).

huangapple
  • 本文由 发表于 2022年3月25日 11:02:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/71611698.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定