'How do I return a struct as json using fiber in golang?
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: "[email protected]",
}
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?
Solution 1:[1]
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: "[email protected]",
}
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | J CHEN |
