Created
March 18, 2023 14:57
-
-
Save simplyluke/ad33c68d8503dd8c0ef5389f4ab9975d to your computer and use it in GitHub Desktop.
ice backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"os" | |
"strconv" | |
"github.com/gin-gonic/gin" | |
"github.com/joho/godotenv" | |
_ "github.com/joho/godotenv/autoload" | |
"github.com/sendgrid/rest" | |
"github.com/sendgrid/sendgrid-go" | |
"github.com/sendgrid/sendgrid-go/helpers/mail" | |
) | |
type emergency_plan struct { | |
Destination string `json:"destination"` | |
GroupMembers string `json:"group_members"` | |
EmergencyContact string `json:"emergency_contact"` | |
Trailhead string `json:"trailhead"` | |
Car string `json:"car"` | |
Clothing string `json:"clothing"` | |
Equipment string `json:"equipment"` | |
PreparedNight bool `json:"prepared_night"` | |
ExpectedReturn string `json:"expected_return"` | |
EmergencyTime string `json:"emergency_time"` | |
RecipientEmail string `json:"recipient_email"` | |
} | |
func main() { | |
godotenv.Load() | |
router := gin.Default() | |
router.POST("/emergency_plan", postEmergencyPlan) | |
router.Run() | |
} | |
func postEmergencyPlan(c *gin.Context) { | |
var plan emergency_plan | |
if err := c.BindJSON(&plan); err != nil { | |
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) | |
return | |
} | |
response, sendgridError := sendEmail(plan) | |
if sendgridError != nil { | |
c.JSON(http.StatusBadRequest, gin.H{"error": sendgridError.Error()}) | |
} | |
c.JSON(response.StatusCode, gin.H{"sendgrid_response": response.Body}) | |
} | |
func sendEmail(plan emergency_plan) (*rest.Response, error) { | |
senderEmail := os.Getenv("SENDER_EMAIL") | |
from := mail.NewEmail("Luke Wright", senderEmail) | |
subject := "Luke Wright has just shared an emergency plan with you" | |
to := mail.NewEmail(plan.RecipientEmail, plan.RecipientEmail) | |
htmlContent := "<p>Luke Wright has just shared an emergency plan with you.</p><p>Destination: " + plan.Destination + "</p><p>Group Members: " + plan.GroupMembers + "</p><p>Emergency Contact: " + plan.EmergencyContact + "</p><p>Trailhead: " + plan.Trailhead + "</p><p>Car: " + plan.Car + "</p><p>Clothing: " + plan.Clothing + "</p><p>Equipment: " + plan.Equipment + "</p><p>Prepared for a night out: " + strconv.FormatBool(plan.PreparedNight) + "</p><p>Expected Return: " + plan.ExpectedReturn + "</p><p>Emergency Time: " + plan.EmergencyTime + "</p>" | |
message := mail.NewSingleEmail(from, subject, to, "", htmlContent) | |
client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY")) | |
return client.Send(message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment