Exemplo n.º 1
0
// ServeHTTPC handles requests as a xhandler.HandlerC
func (h *Handler) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var query string
	switch r.Method {
	case "GET":
		query = r.URL.Query().Get("query")
	case "POST":
		b, _ := ioutil.ReadAll(r.Body)
		r.Body.Close()
		if r.Header.Get("Content-Type") == "application/json" {
			q := map[string]interface{}{}
			if err := json.Unmarshal(b, &q); err != nil {
				http.Error(w, fmt.Sprintf("Cannot unmarshal JSON: %v", err), http.StatusBadRequest)
			}
			query, _ = q["query"].(string)
		} else {
			query = string(b)
		}
	default:
		http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
		return
	}
	result := graphql.Do(graphql.Params{
		Context:       ctx,
		RequestString: query,
		Schema:        h.schema,
	})
	if resource.Logger != nil {
		if len(result.Errors) > 0 {
			resource.Logger(ctx, resource.LogLevelError, fmt.Sprintf("wrong result, unexpected errors: %v", result.Errors), nil)
		}
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(result)
}
Exemplo n.º 2
0
func logErrorf(ctx context.Context, format string, a ...interface{}) {
	if resource.Logger != nil {
		resource.Logger(ctx, resource.LogLevelError, fmt.Sprintf(format, a...), nil)
	}
}