将App Engine应用程序从Go 1.9迁移到Go 1.11

时间:2019-05-17 12:20:01

标签: go

我已将golang版本从1.9更新为1.11。更新sendgrid邮件后,发送无法正常工作。

我关注了以下链接:

https://cloud.google.com/appengine/docs/standard/go111/go-differences

,发现我们需要使用request.Context()或您首选的上下文,而不是使用appengine.NewContext。 但是当我尝试request.Context()时,没有定义请求。

那么如何将 appengine.NewContext更改为go111的request.Context()

这是我的代码:

func SendTestmail(c echo.Context) error {
type output struct {
    Message string      `json:"message"`
    Status  bool        `json:"status"`
}
result := output{}
//mail code
to := "myemail@mail.com"
firstName := c.FormValue("first_name")
subject := "Send Test mail"
msg := "Dear User , " + "\n \n" +
    "You have successfully Tested." + "\n " +
    "Sincerely, " + "\n \n" +
    "Team"
var Body = general.FrameEmailObj(os.Getenv("SENDGRID_SENDER"), subject, to, msg)
url := os.Getenv("SENDGRID_URL")

req, err := http.NewRequest("POST", url, bytes.NewBuffer(Body))
req.Header.Set("Authorization", "Bearer "+os.Getenv("SENDGRID_API_KEY"))
req.Header.Set("Content-Type", "application/json")
ctx := appengine.NewContext(c.Request())
client := urlfetch.Client(ctx)
resp, err := client.Do(req)
if err != nil {
    panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
//end mail code
result.Message = "send mail success."
return c.JSON(http.StatusUnauthorized, result)
}

我在appengine中遇到以下错误:-

PANIC RECOVER https://api.sendgrid.com/v3/mail/send:不是App Engine上下文goroutine

预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

migration document指出,特定于App Engine的uflfetch程序包已被net / http程序包取代。

替换此代码:

ctx := appengine.NewContext(c.Request())
client := urlfetch.Client(ctx)
resp, err := client.Do(req)

具有:

resp, err := http.DefaultClient.Do(req)