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

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序