packagemailgunnerimport("net/http""net/url""strings")// MgClient struct holds our URL and API keytypeMgClientstruct{MgAPIURLstringMgAPIKeystringClient*http.Client}// New returns our MgClient with the proper settingsfuncNew(apiurl,apikeystring)MgClient{returnMgClient{apiurl,apikey,http.DefaultClient,}}// FormatEmailRequest puts everything together for sendingfunc(mgc*MgClient)FormatEmailRequest(from,to,subject,bodystring)(r*http.Request,errerror){data:=url.Values{}data.Add("from",from)data.Add("to",to)data.Add("subject",subject)data.Add("text",body)r,err=http.NewRequest(http.MethodPost,mgc.MgAPIURL+"/messages",strings.NewReader(data.Encode()))iferr!=nil{returnnil,err}r.SetBasicAuth("api",mgc.MgAPIKey)r.Header.Add("Content-Type","application/x-www-form-urlencoded")returnr,nil}
为了使其成为一个真正的模块,我们需要对其进行初始化。
$ go mod init github.com/shindakun/mailgunner
go: creating new go.mod: module github.com/shindakun/mailgunner
$ go mod init example
go: creating new go.mod: module example
$ go build
go: finding github.com/shindakun/mailgunner v1.0.0
go: downloading github.com/shindakun/mailgunner v1.0.0
瞧,这样就不用再用了go get!
下次
我想花点时间研究一下 Go 语言的 Web 服务器,所以我们可能会先做一些简单的服务器。它们可能还达不到生产环境的要求,但把它们放到网上看看实际运行效果应该也挺有意思的。我还有一些其他的小项目想尝试一下,也许我会先做这些,到时候看情况吧。