go中进行接口模拟的方法

If I have a handlerfunc like the one below. What is the best way to "mock" or inject a interface that wraps some object for testing?

func GetOrCreateUser(w http.ResponseWriter, r *http.Request) {
    user := GetUserFromContext(r.Context())
    if created :=user.GetOrCreate(); created {
        smtp.SendEmail(...)
        return
    } else {
        w.Write([]byte("Hello User!"))
    }
}

The only way that I have come by seems to be to do this:

type Mailer interface { SendMail() }

func HandlerWithMailer(m Mailer) http.handlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        user := GetUserFromContext(r.Context())
        if created := user.GetOrCreate(); created {
            m.SendEmail(...)
            return
        } else {                
            w.Write([]byte("Hello User!"))
        }
    }
}

Then calling the mailer like this in the router (using httprouter):

m := mailer.New() // assuming this returns a new mailer
r := httprouter.New()
r.GET("/mailer", HandlerWithMailer(m))

Which could then be tested by making a struct that implements the interface and returns whatever I want, which can be called in the tests. I know this works, but I am wondering if this is the preferred method of testing in Go and if there is any other way to go about accomplishing this.

I would call my handlers from a struct like so:

type Handlers struct {
    mailer *Mailer
}

func(h *Handlers) GetOrCreateUser(w http.ResponseWriter, r *http.Request) {
    user := GetUserFromContext(r.Context())
    if created :=user.GetOrCreate(); created {
        h.mailer.SendEmail(...)
        return
    } else {
        w.Write([]byte("Hello User!"))
    }
}

This way you can instansiate the struct with the implementation of Mailer you want to use.

m := mailer.New() // assuming this returns a new mailer
h := Handlers{&m}

r := httprouter.New()
r.GET("/mailer", h.HandlerWithMailer)

and in your tests

m := mockMailer.New() // assuming this returns a new mailer
h := Handlers{&m}

r := httprouter.New()
r.GET("/mailer", h.HandlerWithMailer)