Go Web API for Sending Emails via Contact Form I've been playing around with Go and finally found a use case for a little web service I could build.
It takes JSON data via an HTTP POST request and sends me an email via Mailgun's API (it's used for a contact form on my website).
I'm new to Go and would love some feedback on what I could do better, anything I missed and where I could do better following the &quot;Go way&quot; of doing things. :)
main.go
package main

import (
    &quot;fmt&quot;
    &quot;log&quot;
    &quot;net/http&quot;
    &quot;os&quot;

    &quot;github.com/gorilla/handlers&quot;
    &quot;github.com/gorilla/mux&quot;
)

var mailgunDomain string = os.Getenv(&quot;MAILGUN_DOMAIN&quot;)
var mailgunAPIKey string = os.Getenv(&quot;MAILGUN_API_KEY&quot;)
var allowedOrigin string = os.Getenv(&quot;ALLOWED_ORIGIN&quot;)
var port string = os.Getenv(&quot;PORT&quot;)

func main() {
    if port == &quot;&quot; {
        panic(&quot;Missing environment variable PORT&quot;)
    }
    if mailgunDomain == &quot;&quot; {
        panic(&quot;Missing environment variable MAILGUN_DOMAIN&quot;)
    }
    if mailgunAPIKey == &quot;&quot; {
        panic(&quot;Missing environment variable MAILGUN_API_KEY&quot;)
    }
    if allowedOrigin == &quot;&quot; {
        panic(&quot;Missing environment variable ALLOWED_ORIGIN&quot;)
    }

    r := mux.NewRouter()

    r.Use(handlers.CORS(
        handlers.AllowedHeaders([]string{&quot;Content-Type&quot;}),
        handlers.AllowedOrigins([]string{allowedOrigin}),
    ))

    r.HandleFunc(&quot;/&quot;, homeHandler).Methods(&quot;GET&quot;)
    r.HandleFunc(&quot;/contact&quot;, HandleContact(mailgunDomain, mailgunAPIKey)).Methods(&quot;POST&quot;, &quot;OPTIONS&quot;)

    log.Fatal(http.ListenAndServe(&quot;:&quot;+port, r))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    fmt.Fprintln(w, &quot;API for maxschmitt.me&quot;)
}

contact.go
package main

import (
    &quot;context&quot;
    &quot;encoding/json&quot;
    &quot;fmt&quot;
    &quot;net/http&quot;
    &quot;os&quot;
    &quot;time&quot;

    &quot;github.com/mailgun/mailgun-go/v4&quot;
)

var mailgunSender string = &quot;email@sender.com&quot;
var mailgunReceiver string = &quot;email@receiver.com&quot;

// HandleContact sends emails to me via the contact form
func HandleContact(mailgunDomain string, mailgunAPIKey string) http.HandlerFunc {
    type body struct {
        Name    string `json:&quot;name&quot;`
        Email   string `json:&quot;email&quot;`
        Message string `json:&quot;message&quot;`
    }

    mg := mailgun.NewMailgun(mailgunDomain, mailgunAPIKey)
    mg.SetAPIBase(mailgun.APIBaseEU)

    return func(w http.ResponseWriter, r *http.Request) {
        var b body

        err := json.NewDecoder(r.Body).Decode(&amp;b)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }

        message := &quot;From: &quot; + b.Name + &quot;&lt;&quot; + b.Email + &quot;&gt;\n\n&quot;
        message += b.Message

        fmt.Fprintln(os.Stdout, &quot;## New message!&quot;)
        fmt.Fprintln(os.Stdout, message+&quot;\n&quot;)

        mgMsg := mg.NewMessage(mailgunSender, &quot;New contact form submission&quot;, message, mailgunReceiver)
        mgMsg.SetReplyTo(b.Email)

        // Create a 10s timeout for sending the message
        ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
        defer cancel()

        resp, id, err := mg.Send(ctx, mgMsg)
        if err != nil {
            fmt.Println(&quot;Error sending contact form submission:&quot;)
            fmt.Println(err)
            http.Error(w, &quot;Something went wrong&quot;, http.StatusInternalServerError)
            return
        }

        fmt.Fprintln(os.Stdout, &quot;Mailgun response:&quot;, resp)
        fmt.Fprintln(os.Stdout, &quot;Mailgun ID:&quot;, id)

        json.NewEncoder(w).Encode(b)
    }
}

I appreciate any feedback! Thanks!
A couple thoughts on contact.go.
Global Variables
In general, it's advised to not use global variables like
var mailgunSender string = &quot;email@sender.com&quot;
var mailgunReceiver string = &quot;email@receiver.com&quot;

Instead, there are a few options. You already have a struct definition inside the HandleContact closure, so you could just move them there. You could also pass them as arguments to HandleContact().
The other alternative could be to define a Mailgun struct with those as fields (and could probably include the mailgunDomain and mailgunAPIKey as well). Then define HandleContact as a method on the Mailgun struct, and use the handler by first creating a new Mailgun with the appropriate values like so:
main.go
mg := Mailgun{
    Sender:   &quot;email@sender.com&quot;,
    Receiver: &quot;email@receiver.com&quot;,
    Domain:   mailgunDomain,
    ApiKey:   mailgunAPIKey,
}
r.HandleFunc(&quot;/contact&quot;, mg.HandleContact()).Methods(&quot;POST&quot;, &quot;OPTIONS&quot;)

contact.go
type Mailgun struct {
    Sender:   string
    Receiver: string
    Domain:   string
    ApiKey:   string
}
func (m *Mailgun) HandleContact() http.HandlerFunc {
    type body struct {
        Name    string `json:&quot;name&quot;`
        Email   string `json:&quot;email&quot;`
        Message string `json:&quot;message&quot;`
    }

    mg := mailgun.NewMailgun(m.Domain, m.APIKey)
    //etc...

I think the biggest advantage to setting it up this way is that it becomes very testable. You can inject whatever settings are appropriate for testing.
Printing
fmt.Printf() outputs to Stdout by default, so the lines
fmt.Fprintln(os.Stdout, &quot;## New message!&quot;)
fmt.Fprintln(os.Stdout, message+&quot;\n&quot;)
// ...
fmt.Fprintln(os.Stdout, &quot;Mailgun response:&quot;, resp)
fmt.Fprintln(os.Stdout, &quot;Mailgun ID:&quot;, id)

are functionally the same as
// Note 2 newlines to keep output identical to your implementation
fmt.Printf(&quot;## New message!\n %s\n\n&quot;, message) 
// ...
fmt.Printf(&quot;Mailgun response: %s\n&quot;, resp)
fmt.Printf(&quot;Mailgun ID: %s\n&quot;, id)

Errors
Don't forget to handle the error from json.NewEncoder(w).Encode(b) at the end of contact.go. As the code is written I don't see any reason why it should ever return an error, you're just re-encoding the body you just decoded and echoing it back to the client. But if you ever change your code and the body is modified in some way it could fail silently and lead to debugging headaches.
Also wondering what the purpose of re-encoding is, you could just store and re-use the original value of r.Body. Did you mean to encode and return the response from Mailgun?