The example code at: https://sendgrid.com/blog/send-email-go-google-app-engine/
My guess this is very old sample code to use sendgrid-go on Google App Engine.
I've attempted 4 permutations and failed each time with:
https://api.sendgrid.com/v3/mail/send: http.DefaultTransport and http.DefaultClient are not available in App Engine. See https://cloud.google.com/appengine/docs/go/urlfetch/
Here is a minimum hardcoded attempt with some logging:
package sendgridgo
import(
"github.com/sendgrid/sendgrid-go"
"fmt"
_"google.golang.org/appengine"
"net/http"
"google.golang.org/appengine/log"
"google.golang.org/appengine"
"google.golang.org/appengine/urlfetch"
_ "github.com/sendgrid/sendgrid-go/helpers/mail"
)
func init(){
http.HandleFunc("/", IndexHandler)
appengine.Main()
}
func IndexHandler (w http.ResponseWriter, r *http.Request){
ctx := appengine.NewContext(r)
log.Infof(ctx, "IndexHandler")
sg := sendgrid.NewSendClient("SENDGRID_API_KEY")
log.Infof(ctx, "%v", sg)
bob := urlfetch.Client(ctx)
log.Infof(ctx, "UrlFetchClient %v", bob)
//resp, err := sg.Send(m)
request := sendgrid.GetRequest("SENDGRID_API_KEY", "/v3/mail/send", "https://api.sendgrid.com")
request.Method = "POST"
request.Body = []byte(` {
"personalizations": [
{
"to": [
{
"email": "darian.hickman@gmail.com"
}
],
"subject": "Sending with SendGrid is Fun"
}
],
"from": {
"email": "darian.hickman@villagethegame.com"
},
"content": [
{
"type": "text/plain",
"value": "and easy to do anywhere, even with Go"
}
]
}`)
resp, err := sendgrid.API(request)
if err != nil{
log.Errorf(ctx, "Failed %v", err)
}
fmt.Fprint(w, resp)
}
The solution is documented in sendgrid.go:
So just do this at the beginning of your send, where ctx is appengine.NewContext(req):
After 8 different attempts, including trying an example published in Google Cloud docs for using Sendgrid, an example from Sendgrid blog, and trying to use deprecated versions of Sendgrid api, I found Sendgrid curl examples at:
https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/curl_examples.html
I then translated the HelloWorld example to into URLFetch usage
One Easter weekend, later, it works!
You were on the right track, but skipped overriding the default
sendgrid
client withurlfetch
client.Explanation
The error occurs as sendgrid tries to fetch a url with the default
net/http
method.Quoting AppEngine Documentation
The workaround is to override the Sendgrid client to use
urlfetch
References