doumengmian1180 2017-11-25 11:20
浏览 85
已采纳

Golang,如何使用结构通过HTTP编写JSON响应?

The Goal:

Using github.com/neelance/graphql-go starwars example, I'm trying to write a JSON response to my ReactJS client. That struct stuff is completely new for me, Golang as well btw.

The question:

What should data variable be in order to get the appropriate response to the following example GraphQL query?

query clientQuery {
  character(id: 1000) {
    name
    appearsIn
  }
}

Additional info:

From what I've read here and there, data must be some kind of struct. I've got plenty of structs available in the example (see starwars.go below).

The Code to be modified (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))
}

REFERENCE 1 - starwars.go

REFERENCE 2 - relay.go

  • 写回答

1条回答 默认 最新

  • dongyong2906 2017-11-25 13:19
    关注

    You question is a bit confusing. You are asking about JSON, but your wanted response is not in a valid JSON format: It looks like you added unrelated GraphQL information.

    I am not sure if this is an question about GraphQL or JSON. I will try to answer it anyway.

    Your example data looks like this, therefore I assume that is the result you want to generate:

    data := `{"data":{"character":{"name":"Luke Skywalker","appearsIn":["NEWHOPE","EMPIRE","JEDI"]}}}`
    

    A clean way to make Go generate a proper JSON is to create Structs which contain the data:

    type Response struct {
        Data Data `json:"data"`
    }
    
    type Data struct {
        Character Character `json:"characer"`
    }
    
    type Character struct {
        Name      string   `json:"name"`
        AppearsIn []string `json:"appearsIn"`
    }
    

    Then you can define the data like this:

        data := Response{
            Data: Data{
                Character: Character{
                    Name:      "Luke Skywalker",
                    AppearsIn: []string{"NEWHOPE", "EMPIRE", "JEDI"},
                },
            },
        }
    

    Perhaps this question isn't about JSON rather than GraphQL. In this case you need to clarify your question.

    References

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)