如何使用Go-Gin高效地调用localhost处理程序?以及如何获取正在运行的url?
我遇到一个情况,在一个杜松子酒处理者里面,我需要呼叫另一个处理者 我认为编写一个新的gin.Context对象很难,所以只需向localhost发出请求就可能更容易了,虽然这不是必需的,但它会通过路由器 有没有更有效的方法可以直接调用另一个处理程序 然而,如何获取正在运行的URL呢?当然,它可以是硬编码的,因为它是已知的,但是有下面这样的函数吗如何使用Go-Gin高效地调用localhost处理程序?以及如何获取正在运行的url?,go,go-gin,Go,Go Gin,我遇到一个情况,在一个杜松子酒处理者里面,我需要呼叫另一个处理者 我认为编写一个新的gin.Context对象很难,所以只需向localhost发出请求就可能更容易了,虽然这不是必需的,但它会通过路由器 有没有更有效的方法可以直接调用另一个处理程序 然而,如何获取正在运行的URL呢?当然,它可以是硬编码的,因为它是已知的,但是有下面这样的函数吗 ts := httptest.NewServer(GetMainEngine()) defer ts.Close() log.Println(GetJ
ts := httptest.NewServer(GetMainEngine())
defer ts.Close()
log.Println(GetJWTMiddleware())
// here ts.URL is the running url in test
req, _ := http.NewRequest("POST", ts.URL + "/u/login", bytes.NewBuffer(loginPostString))
如何仅使用gin就获得
ts.URL
?调用另一个处理程序的最佳方法是不调用。相反,将公共逻辑抽象为一个新函数,并调用它。例如:
func handler1(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path()
row := r.URL.Query().Get("rowid")
/* ... do something here with path and row ... */
w.Write(someResponse)
}
func handler2(w http.ResponseWriter, r *http.Request) {
path := "/some/hard-coded/default"
/* ... call handler1 ... */
}
将此更改为:
func handler1(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path()
row := r.URL.Query().Get("rowid")
someResponse, err := common(path, row)
w.Write(someResponse)
}
func handler2(w http.ResponseWriter, r *http.Request) {
path := "/some/hard-coded/default"
row := r.URL.Query().Get("someRowID")
result, err := common(path, row)
w.Write(result)
}
func common(path, row string) (interface{}, error) {
/* ... do something here with path and row ... */
}
一般来说,调用处理程序函数的唯一方法应该是mux/路由器和单元测试