go-Build GRAPHQL Service side

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

The GRAPHQL interface provided by GitHub is very comprehensive, so how do we build our own interfaces? Fortunately, GRAPHQL offers a number of language solutions. This article mainly explains how to use go to build their own GRAPHQL server. If you know graphql, you should read the GRAPHQL-API query language or related Materials first.

Graphql-go

An
implementation of GRAPHQL in Go. follows the official reference implementation graphql-js .

A more complete framework, it is well known that the structure of go is very friendly to JSON, so there is no need for special processing of data, or very convenient. Open Terminal Input Command

go get github.com/graphql-go/graphql

Object

In server-side programming, everything you write can be called an object . For example, an instance of an item (goods) can have a product name, price, purchase link (URL) three fields. At this point the product can be naturally called an object, and the query statement can be written as:

{    goods{        name        price        url    }}

If at this time we want to query the article two kinds of object information:

/* query 可以省去 */query{     goods{        name    }    article{        name    }}

If you have found that query is like a large object, it has goods and article two fields. In addition to this, mutation also:

mutation{    addGoods(input:goodsInput){        name    }}

This addGoods can be seen as an object that can handle parameters, that is, a function in a sense.

In short, the GRAPHQL server programming is one after another object will form a nested structure (schema) organized, and provide services to the outside.

Query&mutation

To prevent the occurrence of low-level errors, create a new file named Query.go (random) under the current PKG.

import (    "github.com/graphql-go/graphql"    "errors")

Define Good Object

type Goods struct {    ID    string `json:"id"`    Name  string `json:"name"`    Price float64`json:"price"`    Url   string `json:"url"`}var goodsType = graphql.NewObject(    graphql.ObjectConfig{        Name: "Goods",        Fields: graphql.Fields{            "id": &graphql.Field{                Type: graphql.String,            },            "name": &graphql.Field{                Type: graphql.String,            },            "price": &graphql.Field{                Type: graphql.Float,            },            "url": &graphql.Field{                Type: graphql.String,            },        },    },)var goodsListType = graphql.NewList(goodsType)

Note : The array is equivalent to the new object type.

Define the Query object

var querytype = graphql. NewObject (GRAPHQL. objectconfig{Name: "Query", fields:graphql. fields{//No processing parameter "goodslist": &graphql. field{Type:goodslisttype,//Handle the callback function of the struct, and return directly to the structure of the processing complete can be resolve:func (p graph Ql. Resolveparams) (interface{}, error) {return result, err},},// The parameter is the ID "goods": &graphql. field{Type:goodstype, args:graphql. fieldconfigargument{"id": &GRAPHQL. argumentconfig{type:graphql. String,},}, Resolve:func (P graphql. Resolveparams) (interface{}, error) {//Get parameter idquery, IsOK: = p.args["id"]. (  String) If IsOK {return result, nil} err : = errors. New ("Field ' goods ' is missinG Required Arguments:id. ") return nil, Err},},},},

Mutation definition is basically the same, create a new file named Mutation.go:

Defining the Input Object

var goodsInputType = graphql.NewInputObject(    graphql.InputObjectConfig{        Name: "goodsInput",        Fields: graphql.InputObjectConfigFieldMap{            "name": &graphql.InputObjectFieldConfig{                Type: graphql.String,            },            "price": &graphql.InputObjectFieldConfig{                Type: graphql.Float,            },            "url": &graphql.InputObjectFieldConfig{                Type: graphql.String,            },        },    },)

Define mutation Object

var mutationtype = graphql. NewObject (GRAPHQL. objectconfig{Name: "Mutation", fields:graphql. fields{"Addgoods": &graphql. field{Type:goodstype, args:graphql. fieldconfigargument{"Input": &GRAPHQL. Argumentconfig{Type:goodsinputtype,},}, Resolve : Func (P graphql. Resolveparams) (interface{}, error) {input,isok: = p.args["Input"]. ( map[string]string) If!isok{err: = errors.                        New ("Field ' addgoods ' is missing required arguments:input.") Return Nil,err} Result: = goods{name:input["Name"]. ( string), price:input["Price"]. (float64), url:input["Url"]. (string),}//Processing data return Result,err},           },        },    },) 

However, the input type cannot be converted directly to a struct, but is a map[string]interface{} type and requires manual conversion.

Define Schema

var schema, _ = graphql.NewSchema(   graphql.SchemaConfig{      Query:    queryType,      Mutation: mutationType,   },)

At this point, all of our object definitions are complete.

Provision of services

Graphql-go provides a convenient interface for us, and the encapsulated handler can be directly bound to the HTTP package that comes with go.

package apiimport "github.com/graphql-go/handler"func Register() *handler.Handler {   h := handler.New(&handler.Config{      Schema:   &schema,      Pretty:   true,      GraphiQL: true,   })   return h}
func main() {   h := api.Register()   handler := cors.Default().Handler(h)   http.Handle("/graphql", handler)   fmt.Println("The api server will run on port : ", apiPort)   http.ListenAndServe(apiPort, nil)}

Open your browser, visit http://localhost:apiPort/graphql, and see your own GRAPHIQL interface!

Conclusion

If you think this code is not elegant, or even very ugly, that's right. Because I feel the same way, take a look at the next-door Python implementation:

import grapheneclass Query(graphene.ObjectType):  hello = graphene.String()  def resolve_hello(self, args, context, info):    return 'Hello world!'schema = graphene.Schema(query=Query)

There was no rush of old blood.

May be limited with Golang itself reflection system is not perfect, no python various magic methods, no generics, or go itself is not very suitable for writing framework class code. In the process of writing, the redundancy is very much, of course, it may be the problem of the framework itself

Admittedly, go is a very good language, although development efficiency can not be comparable with Python, but in a multi-concurrency environment, go is very good, with a C-level running speed and rich ecology.

Go is still young, other it's getting better!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.