英文:
Golang - Provide return after "if" statement when using framework
问题
它给出了错误missing return at end of function
。我尝试了添加return nil
、return ""
、return 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")
}
这个与其他情况有些不同,比如这里。
没有框架时,它可以正常工作。
英文:
It give error missing return at end of function
. I've tried add return nil
, return ""
, return c.String
, and several others but none works.
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")
}
This one quite different that other case such as in here.
Without framework, it works fine.
答案1
得分: 2
你这里的处理程序不是echo.Get
所期望的,这就是为什么你会得到这个错误:panic: echo: unknown handler
。
为了摆脱这个错误,将你的处理程序更改为类似这样的形式:func(c *echo.Context) error
。
如果你需要从handler
内部访问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")
})
希望能帮到你。
英文:
Your handler here is not what echo.Get
is waiting for that's why you're getting this: panic: echo: unknown handler
.
To get rid of this error change your handler to something like this: func(c *echo.Context) error
If you need to access the http.Request
from inside the handler
you can do it by using the *echo.Context
which also contains a *echo.Response
.
Working solution:
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")
})
Hope it helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论