7

I have been developing in Node/Python for years, and over the holiday I have been trying to expand my knowledge of Go. I have a pet project that I've been working on to learn it.

As I have been reading the gin-gonic documentation, I found syntax that I can't wrap my head around.

func main() {
    router := gin.Default()

    // Simple group: v1
    v1 := router.Group("/v1")
    {
        v1.POST("/login", loginEndpoint)
        v1.POST("/submit", submitEndpoint)
        v1.POST("/read", readEndpoint)
    }

    // Simple group: v2
    v2 := router.Group("/v2")
    {
        v2.POST("/login", loginEndpoint)
        v2.POST("/submit", submitEndpoint)
        v2.POST("/read", readEndpoint)
    }

    router.Run(":8080")
}

Basically, it looks like the router.Group() method takes in a struct, but I am not quite sure what the mechanics are here... It's not wrapped in parentheses. How is this object being passed in/handled by the Group method?

Roman Kiselenko
  • 43,210
  • 9
  • 91
  • 103
Spencer Stolworthy
  • 1,352
  • 10
  • 17

1 Answers1

5

The Go Programming Language Specification

Blocks

A block is a possibly empty sequence of declarations and statements within matching brace brackets.

Declarations and scope

Go is lexically scoped using blocks.


For example, the v1.POST method call statements form a block:

// Simple group: v1
v1 := router.Group("/v1")
{
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
}

This is an unusual use of blocks.

peterSO
  • 158,998
  • 31
  • 281
  • 276
  • 1
    Okay, so basically this is just an arbitrary code block placed after the declaration of variable v1. It's not that the Group method is "ingesting" or taking in the code block, it is just setting it apart to avoid side effects with defer, or something like that? – Spencer Stolworthy Dec 26 '18 at 20:19
  • It can be used for some scoping magic, but it's not here. The code shown would operate exactly identically without the braces. It makes no difference for `defer` which is always function-scoped, not block-scoped. – Adrian Dec 26 '18 at 20:50
  • 1
    Basically the examples from the docs are really terrible and the braces are totally unnecessary decoration. – Adrian Dec 26 '18 at 20:51
  • Thanks so much for your quick response. I was so perplexed. – Spencer Stolworthy Dec 27 '18 at 15:32