Golang客户端执行GraphQL Mutation时出现语法解析错误
问题:使用shurcooL/graphql库调用Strapi GraphQL Mutation报400 Bad Request错误
实际可正常运行的GraphQL Mutation,通过Golang的shurcooL/graphql库发送请求时,出现400 Bad Request错误,错误信息为Syntax Error: Expected Name,错误代码为GRAPHQL_PARSE_FAILED。
相关代码
GraphQL Mutation(手动运行正常)
mutation createQuestion($data:QuestionInput!) { createQuestion(data: $data) { data { id attributes { title description question_id } } } }
Golang结构体定义
CreateQuestion struct { Data struct { ID graphql.ID Attributes struct { Question_id graphql.String Title graphql.String Description graphql.String } } }
变量传递代码
variables := map[string]interface{} { "data": map[string]interface{} { "title": "My testFirst FbPost", "description": "dfsdf is the body of my first post.", "question_id": "35005", }, }
错误原因
最可能的原因是错误使用了client.Query()方法发送Mutation请求。Strapi的GraphQL服务器会将收到的请求解析为Query类型,但Query语法不允许以mutation关键字开头,因此触发解析错误。
另外,结构体定义存在两个问题(虽不是本次语法错误的直接原因,但会导致后续结果解析失败):
- 缺少
type关键字,不符合Golang语法规范 - 结构体字段未添加
graphql标签,无法与GraphQL返回的字段正确映射
解决方法
- 使用
client.Mutate()方法发送Mutation请求,而非client.Query() - 修正结构体定义,添加
type关键字和graphql标签,确保字段映射正确
修正后的完整代码
import ( "context" "fmt" "log" "github.com/shurcooL/graphql" ) // 修正后的结果结构体 type CreateQuestionResult struct { CreateQuestion struct { Data struct { ID graphql.ID `graphql:"id"` Attributes struct { QuestionID graphql.String `graphql:"question_id"` Title graphql.String `graphql:"title"` Description graphql.String `graphql:"description"` } `graphql:"attributes"` } `graphql:"data"` } `graphql:"createQuestion"` } func main() { ctx := context.Background() // 替换为你的Strapi GraphQL地址 client := graphql.NewClient("http://your-strapi-instance/graphql", nil) mutationQuery := `mutation createQuestion($data: QuestionInput!) { createQuestion(data: $data) { data { id attributes { title description question_id } } } }` variables := map[string]interface{}{ "data": map[string]interface{}{ "title": "My testFirst FbPost", "description": "dfsdf is the body of my first post.", "question_id": "35005", }, } var result CreateQuestionResult err := client.Mutate(ctx, &graphql.Mutation{ Query: mutationQuery, Variables: variables, }, &result) if err != nil { log.Fatalf("Mutation执行失败: %v", err) } fmt.Printf("创建的问题ID: %s\n", result.CreateQuestion.Data.ID) }
内容的提问来源于stack exchange,提问作者sridhar chary
相关产品推荐
相关产品推荐

