Please tell me how to bind multi-array to struct - go

type _getData struct {
Title string `json:"title" form:"title"`
Date string `json:"date" form:"date"`
Pages []struct {
Order int `json:"order" form:"title"`
Description string `json:"description" form:"description"`
} `json:"pages" form:"pages"`
func CreateDiary(c echo.Context) error {
var getData _getData
c.Bind(&getData)
fmt.Print(getData)
...
Receive the following data through c.FormParams command, please tell me how to bind it to _getData struct,
map[address:[미국 캘리포니아 산타클라라 카운티 쿠퍼티노 ] date:[2021-10-05] location:[37.32779072192643 -122.01981157064436] map_id:[0] pages[0][description]:[123123] pages[0][order]:[0] pages[1][description]:[123123] pages[1][order]:[1] tags[0][id]:[12] tags[0][tag_name]:[sdf] title:[123123]]
I want to get the data of pages as an array, but I am getting []

You can use 3rd party lib.
import "github.com/monoculum/formam/v3"
type MyFormData struct {
Pages []struct {
Order int `formam:"order"`
Description string `formam:"description"`
} `formam:"pages"`
Tags []struct {
TagName string `formam:"tag_name"`
Id string `formam:"id"`
} `formam:"tags"`
Title string `formam:"title"`
}
func HttpHandler(c echo.Context) error {
myFormData := MyFormData{}
form, err := c.FormParams()
if err != nil {
return err
}
dec := formam.NewDecoder(&formam.DecoderOptions{TagName: "formam"})
dec.Decode(form, &myFormData)
return c.JSON(200, myFormData)
}

Related

Go GraphQL http request: how to get an array of items

How would one aquire an array of all my movies? using an empty interface results in a long string, using the movie struct i get the error decoding response: json: cannot unmarshal number into Go value of type graphql.graphResponse
Any help would be appreciated as I am very new to Go.
type Movie struct {
ID string `json:"id"`
Title string `json:"title"`
Genre string `json:"genre"`
ImgURL string `json:"imgURL"`
Description string `json:"description"`
ReleaseDate int `json:"releaseDate"`
Length string `json:"length"`
Likes int `json:"likes"`
Comments int `json:"comments"`
}
func main() {
graphqlClient := graphql.NewClient("http://localhost:8080/query")
// make a request
graphqlRequest := graphql.NewRequest(`
{
movies {
id,
title,
genre,
imgURL,
description,
releaseDate,
length,
likes,
comments,
}
}
`)
// run it and capture the response
var graphqlResponse []Movie
err := graphqlClient.Run(context.Background(), graphqlRequest, &graphqlResponse)
if err != nil {
panic(err)
}
fmt.Println(graphqlResponse)
}

Error:interface must be a pointer to struct Error Returned in fiber (golang), how to solve this?

I'm new in Golang Programming
I'm Faceing an issue..
I'm trying to acces my sent body data by "BodyParser"functtion
But I got an error
schema: interface must be a pointer to struct
I'm Giving the Function Bellow
func CreateService(c *fiber.Ctx) error {
if c.Locals("user_type") != "1" {
return c.SendString("Wrong One")
}
file, err := c.FormFile("image")
// Check for errors:
if err != nil {
fmt.Println(err.Error())
return c.JSON("Something error")
}
// 👷 Save file to root directory:
c.SaveFile(file, fmt.Sprintf("./%s", file.Filename))
// 👷 Save file inside uploads folder under current working directory:
c.SaveFile(file, fmt.Sprintf("./uploads/%s", file.Filename))
// 👷 Save file using a relative path:
c.SaveFile(file, fmt.Sprintf("/tmp/uploads_relative/%s", file.Filename))
var data map[string]string
if err := c.BodyParser(&data); err != nil {
return err
}
service := models.Services{
Title: data["title"],
Src: PORT + "/" + file.Filename,
}
database.DB.Create(&service)
return c.JSON(service)
}
model.Services is
type Services struct {
Id uint `json:"id"`
Title string `json:"title"`
Src string `json:"src"`
}
Please Help me out. Thanks a lot in advance!!!
We need to provide pointer to a struct in GoFiber_v2 not *map[string]string. This is causing the issue.
Below Function for getting data from GoFiber_v2 BodyParser:
func Register(c *fiber.Ctx) error {
var user models.User
err := c.BodyParser(&user)
if err != nil {
return err
}
fmt.Printf("%#+v", user)
}
Model Package
package models
type User struct {
Id uint `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Email string `json:"email"`
Password string `json:"password"`
}

Parsing Nested JSON string

I am trying to parse a nested json string
I did get it to work by using multiple structs, but I am wondering if I can parse the JSON without using an extra struct.
type Events struct {
Events []Event `json:"events"`
}
type Event struct {
Name string `json:"name"`
Url string `json:"url"`
Dates struct {
Start struct {
LocalDate string
LocalTime string
}
}
}
type Embed struct {
TM Events `json:"_embedded"`
}
func TMGetEventsByCategory(location string, category string) {
parameters := "city=" + location + "&classificationName=" + category + "&apikey=" + api_key
tmUrl := tmBaseUrl + parameters
resp, err := http.Get(tmUrl)
var embed Embed
var tm Event
if err != nil {
log.Printf("The HTTP request failed with error %s\n", err)
} else {
data, _ := ioutil.ReadAll(resp.Body)
err := json.Unmarshal(data, &embed)
json.Unmarshal(data, &tm)
}
}
JSON Data looks like this:
{
"_embedded": {
"events": [],
},
"OtherStuff": {
}
}
Is it possible to get rid of the Embed struct and read straight to the events part of the json string?
What you're looking for here is json.RawMessage. It can help delay parsing of certain values, and in you case map[string]json.RawMessage should represent the top-level object where you can selectively parse values. Here's a simplified example you can adjust to your case:
package main
import (
"encoding/json"
"fmt"
)
type Event struct {
Name string `json:"name"`
Url string `json:"url"`
}
func main() {
bb := []byte(`
{
"event": {"name": "joe", "url": "event://101"},
"otherstuff": 15.2,
"anotherstuff": 100
}`)
var m map[string]json.RawMessage
if err := json.Unmarshal(bb, &m); err != nil {
panic(err)
}
if eventRaw, ok := m["event"]; ok {
var event Event
if err := json.Unmarshal(eventRaw, &event); err != nil {
panic(err)
}
fmt.Println("Parsed Event:", event)
} else {
fmt.Println("Can't find 'event' key in JSON")
}
}
In your case look for the _embedded key and then Unmarshal its value to Events
yes of course
type Embed struct {
TM []struct {
Name string `json:"name"`
Url string `json:"url"`
Dates struct {
Start struct {
LocalDate string
LocalTime string
}
} // add tag here if you want
} `json:"_embedded"`
}

Beego validation accepts invalid data

I am trying to validate some forms using Beego validation, but it is not working at all: invalid data passes without errors.
This the relevant code, I don't know what is wrong. Can you point me at the mistake?
https://github.com/dionyself/golang-cms/blob/master/models/form.go
package models
import (
"github.com/astaxie/beego"
"github.com/astaxie/beego/validation"
)
type BaseForm struct {
Errors map[string]string
}
func (form *BaseForm) Validate() bool {
valid := validation.Validation{}
b, err := valid.Valid(form)
if err != nil {
beego.Error(err)
}
if !b {
for _, err := range valid.Errors {
form.Errors[err.Key] = err.Message
beego.Debug(err.Key, err.Message)
}
}
return b
}
type RegisterForm struct {
BaseForm
Username string `form:"username" valid:"Required; AlphaNumeric; MinSize(4); MaxSize(300)"`
Password string `form:"password" valid:"Required; MinSize(4); MaxSize(30)"`
PasswordRe string `form:"passwordre" valid:"Required; MinSize(4); MaxSize(30)"`
}
func (form *RegisterForm) Valid(v *validation.Validation) {
// Check if passwords of two times are same.
if form.Password != form.PasswordRe {
v.SetError("PasswordRe", "Passwords did not match")
return
}
}
type ArticleForm struct {
BaseForm
Id int `form:"-"`
Title string `form:"title" valid:"Required;MinSize(4);MaxSize(300)"`
Category int `form:"category"`
Content string `form:"content" valid:"Required; MinSize(50); MaxSize(2000)"`
TopicTags string `form:"topic-tags" valid:"MinSize(4); MaxSize(300)"`
TaggedUsers string `form:"tagged-users" valid:"MinSize(4); MaxSize(300)"`
AllowReviews bool `form:"allow-reviews" valid:"Required"`
AllowComments bool `form:"allow-comments" valid:"Required"`
Errors map[string]string
}
func (form *ArticleForm) Valid(v *validation.Validation) {
if form.Category >= 0 {
v.SetError("Category", "Invalid category")
return
}
}
Some documentation:
http://beego.me/docs/mvc/controller/validation.md
This is the code that parses the form:
func (this *ArticleController) Post() {
form := models.ArticleForm{}
Art := new(models.Article)
if err := this.ParseForm(&form); err != nil {
this.Abort("401")
} else {
db := this.GetDB()
if !form.Validate() {
this.Data["form"] = form
var cats []*models.Category
db.QueryTable("category").All(&cats)
this.Data["Categories"] = cats
this.ConfigPage("article-editor.html")
for key, msg := range form.Errors {
fmt.Println(key, msg)
}
} else {
db.Insert(Art)
this.Data["Article"] = Art
this.ConfigPage("article.html")
}
}
}
Note: FormData is always accepted (even an empty form), form.Validate() is always returning 'true'... 0 errors on logs.
It's because your struct has a data type with map[string]interface{} which accepts any data type and converting it into a string try to be specific in data type

Golang jsonapi requires string or int but mongo needs bson.ObjectId

Playing with go and the following packages:
github.com/julienschmidt/httprouter
github.com/shwoodard/jsonapi
gopkg.in/mgo.v2/bson
I have the following structs:
type Blog struct{
Posts []interface{}
}
type BlogPost struct {
Id bson.ObjectId `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}
and this router handler:
func (blog *Blog) GetAll(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
if err := jsonapi.MarshalManyPayload(w, blog.Posts); err != nil {
http.Error(w, err.Error(), 500)
}
}
When the handler function is called it spits out the error:
id should be either string or int
How should this struct look so I can use it with mgo and jsonapi?
Create one more struct of Blog like below
type BlogPostVO struct {
Id string `jsonapi:"primary,posts" bson:"_id,omitempty"`
Author string `jsonapi:"attr,author"`
CreatedDate time.Time `jsonapi:"attr,created_date"`
Body string `jsonapi:"attr,body"`
Title string `jsonapi:"attr,title"`
}
and use the below function in your controller to parse
func parseToVO(blog *models.Blog) *models.BlogVO {
bolgVO := models.BlogVO{}
bolgVO.Id = blog.Id.Hex()
bolgVO.Author = blog.Author
bolgVO.CreatedDate = blog.CreatedDate
bolgVO.Body = blog.Body
bolgVO.Title = blog.Title
return &models.Blog
}
this worked for me

Resources