任何惯用的生成/预处理解决方案库?

I really like Go but makes me crazy about if-err hell and when I have sync datatypes in Go code with other languages. For C/C++ I can easily deal such stuff with macros, while Go developers say the idiomatic solution for Go is code generation, but I didn't find any out-of-the-box solution.

So basically, what I need is something like

  1. Read the source, for every type usage check if it is listed in special config file. If it is, then change it with the one from config.
  2. Read the source, for every function check if it is listed in config file. If it is then, change it with the code snippet from config by template and add neccessary import if it's missing.
  3. Probably, add some polymorphism based on return values to prevent type casts.
  4. Maybe, add (err error) logic. Not sure it's a good idea.

Like this

code.go

func getConn(id platform.UUID) (res1 string, res2 platform.res) {
  res1 = driver_native_res(id)
  res2 = driver_native_res(id)
  return
}

code-gen.go

import (
  "linux"
)
func getConn(id uint64) (res1 string, res2 int32, err error) {
  res1, err = linux.GetResAsString(id)
  if err != nil {
    return
  }
  res2, err = linux.GetRes(id)
  if err != nil {
    return
  }
  return
}

I know about go AST, but seems like it's not very fast to implement such features with it. I hope there is some easier solution.

As you have discovered, there are no macros and are unlikely to be. There may be generics at some point which could be helpful. In the meantime, there are a few options for code generation. You can use go generate for this:

// add a magic comment to your go file 
// which needs some extra generated code
// this calls a tool called stringer to generate, 
// but it could be yacc or some homemade tool. 
//go:generate stringer -type=Pill

// call go generate to generate the methods:
go generate

https://blog.golang.org/generate

But it really requires you to have a tool to generate the code you want like stringer.

Or you could just use text/template, build your own template, and run a simple tool that substitutes values into this template (from a config file, or perhaps arguments on the command line).

mytool generate -type=thing -field=type...
... mytool loads a tmplate file, 
runs it through text/template and outputs it. 

This is pretty straightforward and you could easily build a custom system with it, though you'll probably want to generate once, then use the code. Here are some examples of this approach:

http://clipperhouse.github.io/gen/

https://github.com/fragmenta/fragmenta

Finally, you can use tools like grpc which generate structs in multiple languages in order to ease cross-language communication, which sounds like exactly the use case you are looking for:

https://grpc.io/docs/quickstart/go.html

I'd look at something like grpc first.