Home > Mobile >  GoLang print value of variables in structure
GoLang print value of variables in structure

Time:01-26

I'm not very expert of GoLang, but I need to run troubleshooting on a project. Now I'm try to print the value of same variables, but I receive as output the address and not the value:

attrs := core.Attributes{}
    err = rtrV1.SetAttributesStruct(&attrs, sessAttrs, session.NasIP, ipv4Session, ipv6Session)
    if err1, ok := err.(core.SessionNotFoundError); ok {
        apiH.Logger.Info(err1.Error())
        c.JSON(404, gin.H{"message": err.Error()})
        return
    } else if err != nil {
        apiH.Logger.Error(err.Error())
        c.JSON(500, gin.H{"message": "internal error"})
        return
    }

    err = core.MakeNASProxyRequest(apiH.HttpClient, nasproxyHost, nasproxyPort, authToken, attrs)

    debugAttrs := fmt.Sprintf("% p", attrs)
    debugAttrs2 := fmt.Sprintf("% v", attrs)    
    apiH.Logger.Info("attrs:" " " debugAttrs, log.Field("type", "serve-request"))
    apiH.Logger.Info("attr2:" " " debugAttrs2, log.Field("type", "serve-request"))

I need to print attrs but I receive this output:

"msg":"attrs: %!p(core.Attributes={ 0xc000420460 <nil> <nil>  0xc000238c60 <nil> <nil> <nil> <nil>  0xc000238c98 <nil> <nil> <nil> <nil>})"
"msg":"attr2: {NASIPAddress:0xc000420460 NASIdentifier:<nil> NASIPv6Address:<nil> Username:0xc000238c60 NASPort:<nil> FramedIPAddress:<nil> CalledStationID:<nil> CallingStationID:<nil> AcctSessionID:0xc000238c98 AcctMultiSessionID:<nil> NASPortID:<nil> FramedInterfaceID:<nil> FramedIPv6Prefix:<nil>}"

How can print the value? Thanks for the help

CodePudding user response:

you can use deep pretty printer. Import: github.com/davecgh/go-spew/spew

Example:

spew.Dump(attrs)

CodePudding user response:

you can use fmt package or JSON marshaling to print the struct values... for examples

import "fmt"

type Person struct {
    FirstName string
}

func main() {
    p := &Person{"mr1"}
    fmt.Printf("% v", p)
}

or

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    FirstName string
}

func main() {
    p := &Person{"mr1"}
    s, _ := json.Marshal(p)
    fmt.Printf("%s\n", s)
}
  •  Tags:  
  • Related