If statement Golang-在“之后提供退货”;如果;使用框架时的语句
它在函数结束时给出错误If statement Golang-在“之后提供退货”;如果;使用框架时的语句,if-statement,go,If Statement,Go,它在函数结束时给出错误缺少返回值。我尝试了添加返回nil,返回“”,返回c.String,以及其他一些方法,但都不起作用 package main import ( "github.com/hiteshmodha/goDevice" "github.com/labstack/echo" "net/http" ) func main() { e := echo.New() e.Get("/", func(c *echo.Context, w http.
缺少返回值
。我尝试了添加返回nil
,返回“”
,返回c.String
,以及其他一些方法,但都不起作用
package main
import (
"github.com/hiteshmodha/goDevice"
"github.com/labstack/echo"
"net/http"
)
func main() {
e := echo.New()
e.Get("/", func(c *echo.Context, w http.ResponseWriter, r *http.Request) *echo.HTTPError {
deviceType := goDevice.GetType(r)
if deviceType == "Mobile" {
return c.String(http.StatusOK, "Mobile!")
} else if deviceType == "Web" {
return c.String(http.StatusOK, "Desktop!")
} else if deviceType == "Tab" {
return c.String(http.StatusOK, "Tablet!")
}
})
e.Run(":4444")
}
这一个与另一个案例(如中)完全不同
如果没有框架,它可以正常工作。这里的处理程序不是
echo.Get
正在等待的。这就是为什么您会得到这样的结果:panic:echo:unknown handler
。
若要消除此错误,请将处理程序更改为以下内容:func(c*echo.Context)error
如果需要从处理程序内部访问http.Request
,可以使用*echo.Context
,其中还包含*echo.Response
工作解决方案:
e.Get("/", func(c *echo.Context) error {
deviceType := goDevice.GetType(c.Request())
if deviceType == "Mobile" {
return echo.NewHTTPError(http.StatusOK, "Mobile!")
} else if deviceType == "Web" {
return echo.NewHTTPError(http.StatusOK, "Desktop!")
} else if deviceType == "Tab" {
return echo.NewHTTPError(http.StatusOK, "Tablet!")
}
return echo.NewHTTPError(http.StatusNoContent, "Alien probe")
})
希望能有所帮助@MartinGallagher,我以前也试过这样做。它不适用于错误panic:echo:unknown handler
get errorundefined:echo.NewHTTPError
-是打字错误还是不同的echo版本?另一个,最新版本的Echo使用*Echo.HTTPError
而不是error
我只是去获取Echo的最新版本。我使用的版本还返回一个*echo.HTTPError
,它从Error
接口实现Error()
方法。处理程序似乎能够返回error
和*echo.HTTPError
。我刚刚将echo更新为最新版本,您的解决方案现在就可以运行了。谢谢