Similar to .net attributes in Go - go

What is similar to .net attributes in go lang.
Or how this could be achieved ?

Perhaps the most similar mechanism is Struct Tags. Not the most elegant, but they can be evaluated at runtime and provide metadata on struct members.
From the reflect package documentation: type StructTag
They are used, for example, in JSON and XML encoding for custom element names.
For example, using the standard json package, say I have a struct with a field I don't want to appear in my JSON, another field I want to appear only if it is not empty, and a third one I want to refer to with a different name than the struct's internal name. Here's how you specify it with tags:
type Foo struct {
Bar string `json:"-"` //will not appear in the JSON serialization at all
Baz string `json:",omitempty"` //will only appear in the json if not empty
Gaz string `json:"fuzz"` //will appear with the name fuzz, not Gaz
}
I'm using it to document and validate parameters in REST API calls, among other uses.
If you keep the 'optionally space-separated key:"value"' syntax, you can use the Get Method of StructTag to access the values of individual keys, as in the example.

Related

golang grpc stubs, omit non empty values on marshalling

so I have this fields on my struct (autogenerated)
Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"-"`
Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`
Skipping fields if json marshal is super easy, you just set it to -
Is there a way to do a similar trick with grpc? Don't want to output all fields, also don't want to manually nullify some of the fields on the object, even though it's possible
Thanks

How to unmarshal protbuf data into custom struct in Golang

I have a proxy service that translate protobuf into another struct. I
can just write some manual code to do that, but that is inefficient and boilerplate. I can also transform the protobuf data to JSON, and deserlize the JSON data into the destination struct, but the speed is slow and it is CPU heavy.
The Unmarshaler interface is now deprecated, and Message interface have internal types which I cannot implement in my project.
Is there a way I can do this now?
Psuedo code: basically, if Go's reflection supports setting and getting of struct / class fields by some sort of field identifier, then you can do this. Something like this in C# works, so long as the field types in the two classes are the same (because in C#, I'm doing object = object, which ends up being OK if they're the same actual type).
SourceStructType sourceStruct;
DestStructType destStruct;
foreach (Field sourceField in sourceStruct.GetType().GetFields())
{
Field destField = destStruct.GetType().FindFieldByName(sourceField.name);
destStruct.SetFieldValue(destField) = sourceStruct.GetFieldValue(sourceField);
}
If the structs are more complex - i.e. they have structs within them, then you'll have to recurse down into them. It can get fiddly, but once written you'll never have to write it ever again!

Unmarshal YAML into unknown struct

Sorry for the confusing title, I'm having trouble wording this question. So lets say I have a YAML config file like this
animals:
-
type: whale
options:
color: blue
name: Mr. Whale
features:
-
type: musician
options:
instruments:
- Guitar
- Violin
Very contrived example, but it's directly analogous to what I'm really working with.
So now I have some structs to marshal this config into
type Config struct {
AnimalConfigs []*AnimalConfig `yaml:"animals"`
}
type AnimalConfig struct{
Type string
Options map[string]string // ????
Features []*FeatureConfig
}
type FeatureConfig struct{
Type string
Options ????
}
So the problem here is that the animal types (whale, etc..), and features (musician, etc...) are not determined ahead of time, they can be added on as separate modules and can each have their own configurations. So say someone is using this library and wants to add their own animal. I do not know what this animal is, what it's options will be, and what it's features will be. I also don't know the structure of the feature's. All I know is that it will have a type property, and an options property. I would like the developer to be able to add custom animals and features, and my library can just do something like YourAnimal.Create(yourConfig).
I'm using the go-yaml library. As you can see in the AnimalConfig struct, my initial idea was to have the options and features just be map[string]string, and then let the custom module unmarshal that string into their own struct, but that wouldn't work for example with the musician feature because instruments is a list, not a string. Thanks!
I think in general what you are asking is how to unmarshal YAML when you don't know the structure which will be produced, yes? If so, what I've done is use ghodss/yaml to convert YAML to JSON, then use the standard encoding/json to unmarshal. This gets you a struct with everything in the YAML doc, but you have to "type switch" your way through it, and key names, of course, may not be known a prioir.
Here's an example: https://play.golang.org/p/8mcuot-lw0y
You could make your config of type map[string]interface{} and let the developer using your library decode interface{} into required struct.
Example: https://play.golang.org/p/RVqKP09KR8

In golang what does `something` mean

I have this XML reader struct:
type Recurlyservers struct {
XMLName xml.Name `xml:"servers"`
Version string `xml: "version,attr"`
Svs []server `xml: "server"`
Description string `xml:",innerxml"`
}
What is the meaning of this xml:"servers" or xml: "version,attr"? I don't know what this `` is. I would like to search in Google but I don't know it's name. What is it? and can I use the standard struct without this? Because the XML reading is not working without this.
Those are called field tags. They're used by the xml encoder/decoder to map the property names to the values in the actual data. In your example they're completely necessary because the fields in XML are lower cased, in Go to have fields on a struct exported they have to be upper cased. Since the xml names diverge from the field names on your type, you have to specify what goes where for the encoding package.
This same convention is used from almost all data transformation/encoding/storage libraries.

Best way to validate and extend constructor parameters in Scala 2.10

I want to have a class that has a number of fields such as String, Boolean, etc and when the class is constructed I want to have a fieldname associated with each field and verify the field (using regex for strings). Ideally I would just like specify in the constructor that the parameter needs to meet certain criteria.
Some sample code of how :
case class Data(val name: String ..., val fileName: String ...) {
name.verify
// Access fieldName associated with the name parameter.
println(name.fieldName) // "Name"
println(fileName.fieldName) // "File Name"
}
val x = Data("testName", "testFile")
// Treat name as if it was just a string field in Data
x.name // Is of type string, does not expose fieldName, etc
Is there an elegant way to achieve this?
EDIT:
I don't think I have been able to get across clearly what I am after.
I have a class with a number of string parameters. Each of those parameters needs to validated in a specific way and I also want to have a string fieldName associated with each parameter. However, I want to still be able to treat the parameter as if it was just a normal string (see the example).
I could code the logic into Data and as an apply method of the Data companion object for each parameter, but I was hoping to have something more generic.
Putting logic (such as parameter validation) in constructors is dubious. Throwing exceptions from constructors is doubly so.
Usually this kind of creational pattern is best served with one or more factory methods or a builder of some sort.
For a basic factory, just define a companion with the factory methods you want. If you want the same short-hand construction notation (new-free) you can overload the predefined apply (though you may not replace the one whose signature matches the case class constructor exactly).
If you want to spare your client code the messiness of dealing with exceptions when validation fails, you can return Option[Data] or Either[ErrorIndication, Data] instead. Or you can go with ScalaZ's Validation, which I'm going to arbitrarily declare to be beyond the scope of this answer ('cause I'm not sufficiently familiar with it...)
However, you cannot have instances that differ in what properties they present. Not even subclasses can subtract from the public API. If you need to be able to do that, you'll need a more elaborate construct such as a trait for the common parts and separate case classes for the variants and / or extensions.

Resources