gpt4 book ai didi

if-statement - Golang - 使用框架时在 "if"语句后提供返回

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:59 24 4
gpt4 key购买 nike

它给出错误在函数末尾缺少返回值。我试过添加 return nilreturn ""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")
}

这个与其他案例完全不同,例如 here .

没有框架,它工作正常。

最佳答案

这里的处理程序不是 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")
})

希望对你有帮助

关于if-statement - Golang - 使用框架时在 "if"语句后提供返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30410558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com