download20151010 2017-03-05 07:21
浏览 48
已采纳

golang大猩猩/ mux和测试,在哪里存储路由

In most of the docs I have seen, gorilla mux is suggested to be used like so...

func main() {
    m := mux.Router()
    m.HandleFunc("/", FuncNameOrDef)
    http.ListenAndServe(":8080", m)
}

which is great, but it leaves me with a problem, because then in order to test, as far as I can see, I need to redeclare mux and routes unless I declare mux and routes outside of a function like this...

var (
    m = mux.Router()
    _ = m.HandleFunc("/", FuncNameOrDef)
)

and then in my tests do this...

func TestSomeView(t *testing.T) {
    ts := httptest.NewServer(m)
    ....testing blah
}

which solves the problem, but then it makes the package pretty ugly (with all the _ = m.HandleFunc's) Is there a more idiomatic way to do this?

  • 写回答

1条回答 默认 最新

  • dtmjl4427 2017-03-05 18:44
    关注

    You could use a factory function to create a new http.Handler for you application. This would allow you to programmatically define the handlers and reuse them in the tests.

    // NewApplicationHandler provides a configured handler for the
    // application.
    func NewApplicationHandler() http.Handler {
        mux := mux.NewRouter()
        mux.HandleFunc("/", handler)
    
        return mux
    }
    
    func handler(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World!"))
    }
    

    This example would be utilized in a test like so:

    func TestApplicationServeMux(t *testing.T) {
        // The handlers are being obtained via a call to the factory function.
        applicationHandler := NewApplicationHandler()
    
        ts := httptest.NewServer(applicationHandler)
        defer ts.Close()
    
        res, err := http.Get(ts.URL)
    
        if err != nil {
            t.Fatalf("%s", err)
        }
    
        defer res.Body.Close()
        greeting, err := ioutil.ReadAll(res.Body)
    
        if err != nil {
            log.Fatalf("%s", err)
        }
    
        want := []byte("Hello World!")
    
        if !bytes.Equal(want, greeting) {
            t.Errorf("Expected greeting %s; got %s", want, greeting)
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图