目标:
使用github.com/neelance/graphql-go星战示例,我试图为我的ReactJS客户端编写一个JSON响应。那种结构对我来说是全新的,戈朗也是。
问题:
为了获得对下面的示例data查询的适当响应,GraphQL变量应该是什么?
query clientQuery {
character(id: 1000) {
name
appearsIn
}
}附加信息:
根据我在这里和那里所读到的,data一定是某种结构。我在这个例子中有很多可用的结构(参见下面的starwars.go )。
待修改代码(main.go):
package main
import (
"encoding/json"
"log"
"net/http"
"github.com/neelance/graphql-go"
"github.com/neelance/graphql-go/example/starwars"
"github.com/neelance/graphql-go/relay"
)
var schema *graphql.Schema
func init() {
schema = graphql.MustParseSchema(starwars.Schema, &starwars.Resolver{})
}
func main() {
port := ":8080"
log.Printf(`GraphQL server starting up on http://localhost%v`, port)
http.Handle("/query", &relay.Handler{Schema: schema})
http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) {
// THIS IS SUPER WRONG, data should be something
// like data := starwars.Resolver{} or so?
data := `{"data":{"character":{"name":"Luke Skywalker","appearsIn":["NEWHOPE","EMPIRE","JEDI"]}}}`
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
})
log.Fatal(http.ListenAndServe(port, nil))
}参考文献1 - starwars.go
参考文献2 - relay.go
发布于 2022-08-14 19:59:19
这里有一个简单的例子,如果它在这里的话,它会对我有所帮助。
type Password struct {
Password string `json:"password"`
}
func keyHandler(w http.ResponseWriter, r *http.Request) {
response := Password{"password"}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(response)
}https://stackoverflow.com/questions/47485360
复制相似问题