Skip to content

Instantly share code, notes, and snippets.

@littlefuntik
Last active September 4, 2019 12:04
Show Gist options
  • Save littlefuntik/bb381c3573ab3d59d51afe1446ec2863 to your computer and use it in GitHub Desktop.
Save littlefuntik/bb381c3573ab3d59d51afe1446ec2863 to your computer and use it in GitHub Desktop.
go-micro req server.Request and response
import (
"strings"
"bytes"
"strconv"
"context"
"encoding/json"
api "github.com/micro/go-api/proto"
)
type GraphqlOperation struct {
Query string `json:"query"`
Variables map[string]interface{} `json:"variables"`
Name string `json:"operationName"`
}
func (s *Session) Graphql(ctx context.Context, req *api.Request, rsp *api.Response) (err error) {
// ... some code
// graphql operation structure
// https://graphql.org/learn/serving-over-http/#http-methods-headers-and-body
op := GraphqlOperation{Variables: map[string]interface{}{}}
// fill graphql operation
{
dat := map[string]*api.Pair{}
switch req.Method {
case http.MethodGet:
if req.Get != nil {
dat = req.Get
}
case http.MethodPost:
// from prepared post data
if req.Post != nil {
dat = req.Post
break
}
// set default Content-Type header
if req.Header == nil {
log.Warning("graphql request without content-type header - set application/json automatically", ctx)
req.Header = map[string]*api.Pair{
"Content-Type": {Key: "Content-Type", Values: []string{"application/json"}},
}
}
// use Content-Type header for parse logic
hdrContentType, ok := req.Header["Content-Type"]
if ok {
hdrContentTypeValue := strings.ToLower(strings.Join(hdrContentType.Values, ""))
if strings.Contains(hdrContentTypeValue, "application/graphql") {
op.Query = req.Body
} else {
if !strings.Contains(hdrContentTypeValue, "application/json") {
log.Warning("graphql request with unknown content-type - use application/json automatically", ctx)
}
err = json.Unmarshal([]byte(req.Body), &op)
if err != nil {
log.Warning("graphql request body with unknown format", log.FmtErr(err), ctx)
op.Query = req.Body
}
}
}
}
if value, ok := dat["query"]; ok {
op.Query = value.String()
}
if value, ok := dat["variables"]; ok {
if err := json.Unmarshal([]byte(value.String()), &op.Variables); err != nil {
log.Warning("graphql variables invalid", log.FmtErr(err), ctx)
}
}
if value, ok := dat["operationName"]; ok {
op.Name = value.String()
}
}
// ... some code with variable "op"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment