Endpoints

When working with REST APIs, each resource has a specific endpoint. This endpoint has multiple methods (verbs) which give/take data in a specific manner to enable behavior. However, the approach in GraphQL is the exact opposite. There is typically only a single endpoint. The structure of the data is not fixed; instead, the protocol is totally driven by the client. For example, in retrieving data, the client specifies exactly what it needs.

In Golang, we generally hook up the graphql endpoint as an HTTP handler, as follows:

http.HandleFunc("/graphql", func(w http.ResponseWriter, r *http.Request) { 
         fmt.Println("[in handler]", r.URL.Query()) 
         result:= executeQuery(r.URL.Query()["query"][0], schema) 
         json.NewEncoder(w).Encode(result) 
   }) 
 
   fmt.Println("Graphql server is running on port 8080") 
   http.ListenAndServe(":8080", nil) 

Here executeQuery() is a helper function, which uses the graphql-go.Do() function to handle the graphql queries, using our preceding schema definition:

func executeQuery(query string, schema graphql.Schema) *graphql.Result { 
   result:= graphql.Do(graphql.Params{ 
         Schema:        schema, 
         RequestString: query, 
   }) 
   if len(result.Errors) > 0 { 
         fmt.Printf("wrong result, unexpected errors: %v", result.Errors) 
   } 
   return result 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset