dqnz43863 2015-05-23 08:25
浏览 76
已采纳

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

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条回答 默认 最新

  • dongya0914 2015-05-23 09:44
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?