gqlgen API外部调用返回GraphiQL HTML而非JSON问题求助
问题解决方案
1. 检查外部请求的请求头
gqlgen默认会根据请求头判断返回内容:如果是GET请求且Accept头包含text/html,或者POST请求的Content-Type不是application/json,就会返回GraphiQL界面。外部请求必须携带正确的头信息:
- 必须设置
Content-Type: application/json - 建议设置
Accept: application/json
示例curl请求:
curl -X POST -H "Content-Type: application/json" -d '{"query": "{ yourQuery }"}' http://your-api-domain/graphql
2. 拆分GraphiQL与API路由
把GraphiQL界面和API接口绑定到不同路径,避免路由混淆。修改gqlgen初始化代码:
srv := handler.NewDefaultServer(generated.NewExecutableSchema(generated.Config{Resolvers: &resolvers.Resolver{}})) // GraphiQL界面单独挂载到/graphiql http.Handle("/graphiql", handler.Playground("GraphQL Playground", "/graphql")) // API接口挂载到/graphql http.Handle("/graphql", srv) log.Fatal(http.ListenAndServe(":8080", nil))
之后外部请求直接访问/graphql即可处理API请求,不会返回HTML界面。
3. 给API路由添加请求头校验中间件
强制API路径只接受符合要求的请求,不符合则直接返回错误:
func jsonOnlyMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost && r.Header.Get("Content-Type") != "application/json" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("Content-Type must be application/json")) return } next.ServeHTTP(w, r) }) } // 给API路由应用中间件 http.Handle("/graphql", jsonOnlyMiddleware(srv))
内容的提问来源于stack exchange,提问作者megajon
相关产品推荐
相关产品推荐

