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

Go+Protobuf+SQL Server API启动正常但请求返回code:5问题排查

问题原因及解决方法

核心问题:路由未注册到正确的ServeMux

你的HTTP服务器监听7778端口时,使用的是grpc-gateway的runtime.ServeMux实例(变量mux),但你把/api/query的handler注册到了全局的http.DefaultServeMux,导致mux中没有这个路由规则,所以请求返回404(对应gRPC Gateway的code:5)。

修复步骤

修改main函数中的路由注册代码,将http.HandleFunc替换为mux.HandleFunc:

// 替换原来的http.HandleFunc
mux.HandleFunc("/api/query", func(w http.ResponseWriter, r *http.Request) {
    startDate := r.URL.Query().Get("startDate")
    endDate := r.URL.Query().Get("endDate")

    req := &pb.QueryRequest{
        ReportStartDate: startDate,
        ReportEndDate:   endDate,
    }
    fmt.Print(req)
    resp, err := (&appServer{db: db}).ExecuteQuery(r.Context(), req)
    if err != nil {
        log.Printf("Error executing query: %v", err)
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(resp.Responses)
})

额外优化建议

  • 复用appServer实例:当前代码在handler中每次新建&appServer{db: db},可以提前创建一个全局实例(比如server := &appServer{db: db}),在注册gRPC服务和HTTP handler时都复用它,避免重复初始化。
  • 检查gRPC Gateway的TLS配置:你的gRPC服务器没有启用TLS,但在注册Gateway时使用了grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")),这会导致Gateway连接gRPC服务时出错。如果gRPC服务没启用TLS,应该改用:
    opts := []grpc.DialOption{grpc.WithInsecure()}
    

内容的提问来源于stack exchange,提问作者nb_nb_nb

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:35:03