Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang accessing elements of Gin.H

Tags:

go

go-gin

trying out the example to find out if the it can be a pubsub, I wonder if it is possible to parse or access the elements in gin.H map. I want to send a Json in a POST.

roomPOST() @ route.go

    ...
    post := gin.H{
        "message": "{\"12345\":\"on\",\"23456\":\"off\",}",
    }
    ...

And I wish to do something with it in streamRoom()

streamRoom() @ route.go

    ...
    c.Stream(func(w io.Writer) bool {
        select {
        case msg := <-listener:
            ...
            fmt.Printf("msg: %s %s\n", reflect.TypeOf(msg), msg)
            ...
    }

msg: gin.H map[message:{"12345":"on","23456":"off"}]

When trying to access the element in msg, e.g.

element := msg["message"].(string)

it throws:

invalid operation: cannot index msg (variable of type interface{})

Please advise how I can access the elements of Gin.H.

like image 770
Simon Avatar asked Jan 21 '26 11:01

Simon


1 Answers

I wonder if it is possible to parse or access the elements in gin.H map

gin.H is defined as type H map[string]interface{}. You can index it just like a map.

In your code, msg is an interface{} whose dynamic type is gin.H, as seen from the output of reflect.TypeOf, so you can't index it directly. Type-assert it and then index it:

content := msg.(gin.H)["message"]
like image 90
blackgreen Avatar answered Jan 24 '26 13:01

blackgreen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!