JS Write code Generation script, JSON to generate the corresponding go type Object
Used for JSON conversion
JS script is not very dependent, can run directly
Change the file as needed before executing
Example
varTopname= "Data";varDefaulttype= "string";varbson=true;//corresponding MongoDBvarjson=true;//HTTP ResponsevarScheme=false;//http Request->schemevarJdata={ "_id": "564d5162e54b3106fb7badea", "macs" : [ "00-21-26-00-c8-b0" ], "time": 1447907400, "timestr": "2015-11-19 12:30", "shop":{ "name": "shop1" }}; String.prototype.firstToUpperCase=function(){ return this[0].touppercase () + this. substring (1);}varFun= (function(){ varotherobj=[]; vargoobjstring= ""; functiongetstruct (data,collectionname) {goobjstring+ = "type" +collectionname.firsttouppercase () + "struct {\ n"; varper= "\ t"; for(varKeyinchData) { varnewkey=Key.firsttouppercase (); Goobjstring+=per +newkey+ "" +GetType (data[key],key); if(json| | bson| |Scheme) {goobjstring+ = "; varTemparr=[] if(json) {temparr.push (' Json: ' ' +key+ ' '); } if(bson) {temparr.push (' Bson: ' +key+ ' '); } if(scheme) {temparr.push (' Scheme: ' ' +key+ ' '); } goobjstring+=temparr.join (""); Goobjstring+ = "; } goobjstring+ = "\ n"; } goobjstring+ = "}\n"; while(otherobj.length>0){ varsubobj=Otherobj.pop (); Getstruct (subobj.obj,subobj.key)}returngoobjstring}functiongetType (obj,key) {varType=defaulttype; if(obj) {Switch(obj.constructor) { caseArray:type= "[]" +gettype (obj[0]| | ""), Key.firsttouppercase ()); break; caseObject:otherobj.push ({key:key,obj:obj}); Type=key.firsttouppercase () break; caseString:type= "string" break; caseNumber:type= "int" break; caseBoolean:type= "bool" break; default : } } returntype; } returnGetstruct}) () console.log (fun (jdata,topname))
Results
Type Data struct {
_id string ' json: ' _id ' bson: ' _id '
Macs []string ' json: "Macs" bson: "Macs" '
Time int ' json: ' time ' bson: ' time '
Timestr string ' json: ' timestr ' bson: ' timestr '
Shop Shop ' Json: shop ' bson: ' shop '
}
Type shop struct {
Name string ' json: ' name ' bson: ' name ' '
}
The code was written before the assistant Go development
The web framework for Go
Https://github.com/cclient/gowebframework
Code path
Https://github.com/cclient/gowebframework/blob/master/tool/code.js
JSON conversion to go class file, js script, nodejs execution