FAQ
Hi,

I'm trying to inject a DB connection into my HTTP handlers using net/http/httptest.

This is what I am currently doing, which seems to work:

// Create a handler instance with a reference to the DB
handler := New(db)

// Wrap the function I want to test
closure := http.HandlerFunc(func (w http.ResponseWriter, r *http.Request {handler.DoSomething(w,r)} )

// After creating the test server, I can execute my tests
server := httptest.NewServer(closure)


I'd like to somehow wrap the creation of the closure in order to reduce code verbosity. Is there some way to declare a function that takes my handler.DoSomething(w,r) as a pointer and wraps it with the http.Handler interface?

Or have I maybe misunderstood how to effectively use anonymous interface implementations?

Or is there potentially a better way to inject shared state into HTTP handlers?

Cheers,

Ben


--

Search Discussions

  • Ben Hood at Jan 21, 2013 at 7:17 pm
    I think I may have answered my own question:

    If I extend my handlers to have the following signature:

    (http.ResponseWriter, *http.Request, *storage.DB)

    where storage.DB is my own custom DB pointer, I can inject the target handler instance in my tests in this way:

    func wrapHandler(fn func (http.ResponseWriter, *http.Request, *storage.DB)) (http.HandlerFunc, error) {

    store, err := storage.Connect("localhost")

    if err != nil {
    return nil, err
    }

    return func(w http.ResponseWriter, r *http.Request) {
    fn(w,r, store)
    }, nil
    }


    Hopefully this is vaguely idiomatic Go.

    On Monday, 21 January 2013 at 18:35, Ben Hood wrote:

    Hi,

    I'm trying to inject a DB connection into my HTTP handlers using net/http/httptest.

    This is what I am currently doing, which seems to work:

    // Create a handler instance with a reference to the DB
    handler := New(db)

    // Wrap the function I want to test
    closure := http.HandlerFunc(func (w http.ResponseWriter, r *http.Request {handler.DoSomething(w,r)} )

    // After creating the test server, I can execute my tests
    server := httptest.NewServer(closure)


    I'd like to somehow wrap the creation of the closure in order to reduce code verbosity. Is there some way to declare a function that takes my handler.DoSomething(w,r) as a pointer and wraps it with the http.Handler interface?

    Or have I maybe misunderstood how to effectively use anonymous interface implementations?

    Or is there potentially a better way to inject shared state into HTTP handlers?

    Cheers,

    Ben
    --

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedJan 21, '13 at 6:36p
activeJan 21, '13 at 7:17p
posts2
users1
websitegolang.org

1 user in discussion

Ben Hood: 2 posts

People

Translate

site design / logo © 2022 Grokbase