Go JSON Naming Strategy

I am very new to Go, and I was exploring the possibility of using one of my microservices. I was wondering how Go converts objects to Json and back to Json. But, unfortunately, I found that setting the names of the output fields is difficult using tag names.

type MyStruct strust{
   MyName string
}

converted to json

{
    "MyName" : "somestring"
}

But we follow a naming strategy for the entire api through the Organization to follow snake_case

{
        "my_name" : "somestring"
}

In my organization is considered valid.

I started using type tags json:"my_name,omitempty", etc. at field level.

I would like to know if there is a way to configure it at the global level of the project, so I do not want to take care of this at every object and its field level.

+4
1

- : https://play.golang.org/p/i5X69ywjup

:

// SnakeCaseEncode snake_case the given struct field names.
func SnakeCaseEncode(i interface{}) map[string]interface{} {
    rt, rv := reflect.TypeOf(i), reflect.ValueOf(i)

    if rt.Kind() == reflect.Ptr {
        i := reflect.Indirect(rv).Interface()
        rt, rv = reflect.TypeOf(i), reflect.ValueOf(i)
    }

    out := make(map[string]interface{}, rt.NumField())

    for i := 0; i < rt.NumField(); i++ {
        if strings.Contains(rt.Field(i).Tag.Get("json"), "omitempty") {
            continue
        }

        k := snakeCase(rt.Field(i).Name)

        out[k] = rv.Field(i).Interface()
    }

    return out
}

// snakeCase provides basic ASCII conversion of camelCase field names to snake_case.
func snakeCase(s string) string {
    out := make([]rune, 0, utf8.RuneCountInString(s))

    for i, r := range s {
        if r >= 'A' && r <= 'Z' {
            r += 32

            if i > 0 {
                out = append(out, '_')
            }
        }

        out = append(out, r)
    }

    return string(out)
}

, .., .

+3

Source: https://habr.com/ru/post/1649491/


All Articles