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

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)
}

Related

Creating new shopify article with the same content gives errors

Following is my code and struct for creating shopify articles. I never had a issue with them until recently where some of the pages get created and others send a 422 Unprocessable Entity response. can someone help me sorting this out as i dont see an issue here..!
pageArticle := &ArticleRequest{
Article: Article{
Title: FinalTitle,
Author: "Hit Parader",
Tags: Tags,
BodyHTML: html,
PublishedAt: time.Now().UTC().Format("2006-01-02T15:04:05-0700"),
Image: ArticleImage{
Src: pageSRC,
Alt: title,
},
Metafields: []ArticleMeta{
{
Key: "feature_image_page_number",
Value: page,
Type: "number_integer",
Namespace: "custom",
},
},
},
}
spew.Dump(pageArticle)
articleJSON2, err := json.Marshal(pageArticle)
if err != nil {
fmt.Println(err)
}
articleReq2, err := http.NewRequest("POST", newArticleQueryFinal, bytes.NewBuffer(articleJSON2))
if err != nil {
fmt.Println(err)
}
articleReq2.Header.Add("X-Shopify-Access-Token", token)
articleReq2.Header.Add("Content-Type", "application/json")
resp3, err := client.Do(articleReq2)
if err != nil {
fmt.Println(err)
}
Struct
type ArticleRequest struct {
Article Article `json:"article"`
}
type Article struct {
Title string `json:"title"`
Author string `json:"author"`
Tags string `json:"tags"`
BodyHTML string `json:"body_html"`
PublishedAt string `json:"published_at"`
Image ArticleImage `json:"image"`
Metafields []ArticleMeta `json:"metafields"`
}
type ArticleImage struct {
Src string `json:"src,omitempty"`
Alt string `json:"alt,omitempty"`
}
type ArticleMeta struct {
Key string `json:"key"`
Value int `json:"value"`
Type string `json:"type"`
Namespace string `json:"namespace"`
}
same kind of content gives 2 response types. Im at a loss here.
Any help would be appreciated..!!!

Please tell me how to bind multi-array to struct

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)
}

How to get JSON response body from http.Get

I'm trying get body from response which is json and print this json or be able to put him to array. I find this post on stack: How to get JSON response from http.Get .
There is code:
var myClient = &http.Client{Timeout: 10 * time.Second}
func getJson(url string, target interface{}) error {
r, err := myClient.Get(url)
if err != nil {
return err
}
defer r.Body.Close()
return json.NewDecoder(r.Body).Decode(target)
}
but I don't undestand why there is "Decode(target)" and "target interface{}". What does it do? Why when I try just print json.NewDecoder(r.Body) there is nothing meaningful.
The function getJson in the question decodes the JSON response body for the specified URL to the value pointed to by target. The expression json.NewDecoder(r.Body).Decode(target) does the following:
create a decoder that reads from the response body
use the decoder to unmarshal the JSON to the value pointed to by target.
returns error or nil.
Here's an example use of the function. The program fetches and prints information about this answer.
func main() {
url := "https://api.stackexchange.com/2.2/answers/67655454?site=stackoverflow"
// Answers is a type the represents the JSON for a SO answer.
var response Answers
// Pass the address of the response to getJson. The getJson passes
// that address on to the JSON decoder.
err := getJson(url, &response)
// Check for errors. Adjust error handling to match the needs of your
// application.
if err != nil {
log.Fatal(err)
}
// Print the answer.
for _, item := range response.Items {
fmt.Printf("%#v", item)
}
}
type Owner struct {
Reputation int `json:"reputation"`
UserID int `json:"user_id"`
UserType string `json:"user_type"`
AcceptRate int `json:"accept_rate"`
ProfileImage string `json:"profile_image"`
DisplayName string `json:"display_name"`
Link string `json:"link"`
}
type Item struct {
Owner *Owner `json:"owner"`
IsAccepted bool `json:"is_accepted"`
Score int `json:"score"`
LastActivityDate int `json:"last_activity_date"`
LastEditDate int `json:"last_edit_date"`
CreationDate int `json:"creation_date"`
AnswerID int `json:"answer_id"`
QuestionID int `json:"question_id"`
ContentLicense string `json:"content_license"`
}
type Answers struct {
Items []*Item `json:"items"`
HasMore bool `json:"has_more"`
QuotaMax int `json:"quota_max"`
QuotaRemaining int `json:"quota_remaining"`
}
Link to complete code including code from question.
Here is an example:
package main
import (
"encoding/json"
"net/http"
)
func main() {
r, e := http.Get("https://github.com/manifest.json")
if e != nil {
panic(e)
}
defer r.Body.Close()
var s struct { Name string }
json.NewDecoder(r.Body).Decode(&s)
println(s.Name == "GitHub")
}
https://golang.org/pkg/encoding/json#Decoder.Decode

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"`
}

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