What is the problem of Go in this context syntactically?

Issue

I was trying to write a function but the issue here surprised me.

userGroup.Use(
        middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error)  {
            if username == "joe" && password == "123"{
                return true, nil
            }
            return false, nil
        })  // <- error happens here
    )
userGroup.Use(
        middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error)  {
            if username == "joe" && password == "123"{
                return true, nil
            }
            return false, nil
        })) // <- !!

Spent an hour for a bug but turns out the last closing parentheses must not float around. Is this an issue with semicolons, commas or indentation?
I remember JS not caring about this kind of stuff
The error I was getting was :

missing ',' before newline in argument list |syntax

Solution

This is the result of Golang’s semi-colon rule: https://go.dev/doc/effective_go#semicolons, where Go is adding a semicolon as it scans the source, so the original source is free of semicolon.

Following the rule "if the newline comes after a token that could end a statement, insert a semicolon", your earlier code would look like below:

userGroup.Use(
        middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error)  {
            if username == "joe" && password == "123"{
                return true, nil
            }
            return false, nil
        });  // <- semicolon added here
    )

which of course wrong and causes an error. Moving the closing parentheses on that line instead fixes that.

Answered By – Harits Elfahmi

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.