apasajja
apasajja

Reputation: 606

Golang - Provide return after "if" statement when using framework

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.

Upvotes: 0

Views: 1216

Answers (1)

Ganitzsh
Ganitzsh

Reputation: 351

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

Upvotes: 2

Related Questions