天天看點

graphql學習(一)

Golang的 GraphQL 庫主要有兩個:

Graphql-go/graphql: Code-First 模式的庫,無需編寫 GraphQL SDL,通過 Go 自帶的結構體來描述 GraphQL 中的資料類型,由庫本身來轉換為 GraphQL Schema。

graph-gophers/graphql-go: Schema-First 模式的庫,需要先寫好 SDL,然後在 Go 中寫相應的字段的解析函數。

以上的話什麼意思,我也不是很明白,反正選擇星星更多的沒錯,是以選擇第一個.

package main

import (

"fmt"

"github.com/graphql-go/graphql"

)

func main() {

    fmt.Println(&graphql.Schema{})

}           

編譯後控制台應該輸出:

API server listening at: 127.0.0.1:11559
&{map[] [] <nil> <nil> <nil> map[] map[] []}
Process exiting with code: 0           

首先确定了import是正确無誤了.

初學都得來一段"hello, world". 官網上的hello world是控制台輸出的,我們要的是可以從浏覽器輸出.

很多地方都是配合gin架構做,其實官網上有提供handler庫,配合标準庫net/http就可以了.

package main

import (
    "net/http"

    "github.com/graphql-go/graphql"
    "github.com/graphql-go/handler"
)

// 處理查詢請求
var queryHello = graphql.Field{
    Name:        "QueryHello",
    Description: "Query Hello",
    Type:        graphql.String,
    // Resolve是一個處理請求的函數,具體處理邏輯可在此進行
    Resolve: func(params graphql.ResolveParams) (interface{}, error) {
        return "hello,world", nil
    },
}

// 定義根查詢節點
var rootQuery = graphql.NewObject(graphql.ObjectConfig{
    Name:        "RootQuery",
    Description: "Root Query",
    Fields: graphql.Fields{
        "hello": &queryHello, // 這裡的hello,你可以試着改變一下,比如改成test,看看GraphiQL哪裡會有變化
    },
})

// 定義Schema用于http handler處理
var schema, _ = graphql.NewSchema(graphql.SchemaConfig{
    Query:    rootQuery, // 查詢用
    Mutation: nil,       // 需要通過GraphQL做增删改,可以定義Mutation
})

// main
func main() {
    h := Register()
    http.Handle("/graphql", h)
    http.ListenAndServe(":8080", nil)
}

// 初始化handler
func Register() *handler.Handler {
    h := handler.New(&handler.Config{
        Schema:   &schema,
        Pretty:   true,
        GraphiQL: true,
    })
    return h
}           

打開浏覽器,位址欄輸入

http://127.0.0.1:8080/graphql,

就可以看到GraphiQL界面:

graphql學習(一)

輸入{hello},就可以在右側看到hello world了

graphql學習(一)