go-kratos / kratos

Your ultimate Go microservices framework for the cloud-native era.
https://go-kratos.dev
MIT License
23.43k stars 4.01k forks source link

[Feature] Add convenient functions to return official codec in encoding package. #3396

Closed kvii closed 3 months ago

kvii commented 3 months ago

Currently (kratos version v2.8.0), getting a specific codec is too cumbersome. It requires importing an additional package and has potential package conflict risk. For example, if I want to use the YAML codec, I need to do the following:

import "github.com/go-kratos/kratos/v2/encoding"
import "github.com/go-kratos/kratos/v2/encoding/yaml" // Import an additional package
codec := encoding.GetCodec(yaml.Name) // The yaml package has a name conflict, making it difficult to import

Consider adding convenience functions for the official codec implementations to simplify this process, like so:

import "github.com/go-kratos/kratos/v2/encoding" // Only import one package
codec := encoding.YamlCodec() // Directly input Yaml and get auto-completion without conflicts

brief translate:

现在想获取一个特定的 codec 太啰嗦了。得多 import 一个对应的 package,并且还可能导致包名冲突。 可以考虑给官方的 codec 们添加一个简化函数,直接一步到位。

kvii commented 3 months ago

An example to describe package conflict.

"github.com/go-kratos/kratos/v2/encoding"
"github.com/go-kratos/kratos/v2/encoding/json"
encoding.GetCodec(json.Name)

"encoding/json" // has conflict
var _ json.RawMessage
shenqidebaozi commented 3 months ago

There doesn't seem to be any fundamental difference, but a list of functions has been added

kvii commented 3 months ago

Let's find some examples in standard library.

They are fundamentally the same, but they have been included in standard library.

xchwan commented 3 months ago

it seems we need to have XmlCodec(), JsonCodec()....

kvii commented 3 months ago

It's too embarrassed. The official encoders, like json, are depend on "encoding" . So "encoding" can't provide convenient functions like JsonCodec because that will cause package conflict. And there isn't any proper place to define those functions. It's not fluent when I'm using yaml codec for my code. But I have no idea to improve it.