Golang迁移到v112版本遇到问题如何解决

Golang迁移到v112版本遇到问题如何解决 我的网站已离线,我在将网站迁移到 Go 1.12 版本时遇到了问题。

我该如何将这段代码从 appengine/urlfetch 迁移到 net/http

func myHandler(w http.ResponseWriter, r *http.Request) {

some code…

}

// 下面的代码无法工作
// 获取 URL 请求
ctx := appengine.NewContext( r )
client := urlfetch.Client(ctx)

非常感谢 smiley


更多关于Golang迁移到v112版本遇到问题如何解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html

2 回复

我通过一些搜索和试错,成功修复了网站。我已经超过三年没有更新这个网站了,所以对Golang和Google云服务的使用有些生疏了。

将URL请求代码从urlfetch迁移到net/http是相对简单的部分,但我还必须在Google Cloud中注册账单。这没问题,因为我每月都有免费额度,而且网站消耗的资源不多。完成这一步后,网站就正常工作了。

最令人困惑的部分是,我试图按照网上找到的说明让导入appengine命令生效,但我无法部署网站。后来我发现,我已经不再需要导入appengine了,所以直接删掉它就好……

import {
           "other stuff.."
           //"google.golang.org/appengine"
          }

我只需要做这个改动。

            //// 旧代码
			//// 获取URL请求
			//ctx := appengine.NewContext(r)
			//client := urlfetch.Client(ctx)
			//resp, err := client.Get(req.URL.String())
			
			//// golang 1.13
			resp, err := http.Get(req.URL.String())

另外,对app.yaml文件等也做了一些修改,这些说明可以在网上找到。

更多关于Golang迁移到v112版本遇到问题如何解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


从 Go 1.11 开始,App Engine 标准环境不再需要特殊的 urlfetch 包,可以直接使用标准的 net/http 客户端。以下是迁移方案:

func myHandler(w http.ResponseWriter, r *http.Request) {
    // 直接使用标准 http.Client
    client := &http.Client{
        Timeout: time.Second * 30, // 建议设置超时
    }
    
    // 发起请求示例
    resp, err := client.Get("https://api.example.com/data")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()
    
    // 处理响应...
}

如果需要保留上下文(如请求超时控制),可以使用 http.NewRequestWithContext

func myHandler(w http.ResponseWriter, r *http.Request) {
    client := &http.Client{}
    
    // 使用请求的上下文
    req, err := http.NewRequestWithContext(r.Context(), "GET", "https://api.example.com/data", nil)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    
    resp, err := client.Do(req)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer resp.Body.Close()
    
    // 处理响应...
}

对于需要自定义传输层的情况:

func myHandler(w http.ResponseWriter, r *http.Request) {
    client := &http.Client{
        Transport: &http.Transport{
            MaxIdleConns:        100,
            IdleConnTimeout:     90 * time.Second,
            TLSHandshakeTimeout: 10 * time.Second,
        },
        Timeout: 30 * time.Second,
    }
    
    // 使用客户端发起请求...
}

删除所有 appengine 包的导入,使用标准的 net/http 客户端即可在 Go 1.12 中正常工作。

回到顶部