You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 05:17:02