repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/model/sql/converter/types_test.go
tools/goctl/model/sql/converter/types_test.go
package converter import ( "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/ddl-parser/parser" ) func TestConvertDataType(t *testing.T) { v, _, err := ConvertDataType(parser.TinyInt, false, false, true) assert.Nil(t, err) assert.Equal(t, "int64", v) v, _, err = ConvertDataType(parser.TinyInt, false, true, true) assert.Nil(t, err) assert.Equal(t, "uint64", v) v, _, err = ConvertDataType(parser.TinyInt, true, false, true) assert.Nil(t, err) assert.Equal(t, "sql.NullInt64", v) v, _, err = ConvertDataType(parser.Timestamp, false, false, true) assert.Nil(t, err) assert.Equal(t, "time.Time", v) v, _, err = ConvertDataType(parser.Timestamp, true, false, true) assert.Nil(t, err) assert.Equal(t, "sql.NullTime", v) v, _, err = ConvertDataType(parser.Decimal, false, false, true) assert.Nil(t, err) assert.Equal(t, "float64", v) } func TestConvertStringDataType(t *testing.T) { type ( input struct { dataType string isDefaultNull bool unsigned bool strict bool } result struct { goType string thirdPkg string isPQArray bool } ) var testData = []struct { input input want result }{ { input: input{ dataType: "bigint", isDefaultNull: false, unsigned: false, strict: false, }, want: result{ goType: "int64", }, }, { input: input{ dataType: "bigint", isDefaultNull: true, unsigned: false, strict: false, }, want: result{ goType: "sql.NullInt64", }, }, { input: input{ dataType: "bigint", isDefaultNull: false, unsigned: true, strict: false, }, want: result{ goType: "uint64", }, }, { input: input{ dataType: "_int2", isDefaultNull: false, unsigned: false, strict: false, }, want: result{ goType: "pq.Int64Array", isPQArray: true, }, }, } for _, data := range testData { tp, thirdPkg, isPQArray, err := ConvertStringDataType(data.input.dataType, data.input.isDefaultNull, data.input.unsigned, data.input.strict) assert.NoError(t, err) assert.Equal(t, data.want, result{ goType: tp, thirdPkg: thirdPkg, isPQArray: isPQArray, }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/model/sql/converter/types.go
tools/goctl/model/sql/converter/types.go
package converter import ( "fmt" "strings" "github.com/zeromicro/ddl-parser/parser" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/pkg/env" ) var unsignedTypeMap = map[string]string{ "int": "uint", "int8": "uint8", "int16": "uint16", "int32": "uint32", "int64": "uint64", } var commonMysqlDataTypeMapInt = map[int]string{ // For consistency, all integer types are converted to int64 // number parser.Bit: "byte", parser.TinyInt: "int64", parser.SmallInt: "int64", parser.MediumInt: "int64", parser.Int: "int64", parser.MiddleInt: "int64", parser.Int1: "int64", parser.Int2: "int64", parser.Int3: "int64", parser.Int4: "int64", parser.Int8: "int64", parser.Integer: "int64", parser.BigInt: "int64", parser.Float: "float64", parser.Float4: "float64", parser.Float8: "float64", parser.Double: "float64", parser.Decimal: "float64", parser.Dec: "float64", parser.Fixed: "float64", parser.Numeric: "float64", parser.Real: "float64", // date&time parser.Date: "time.Time", parser.DateTime: "time.Time", parser.Timestamp: "time.Time", parser.Time: "string", parser.Year: "int64", // string parser.Char: "string", parser.VarChar: "string", parser.NVarChar: "string", parser.NChar: "string", parser.Character: "string", parser.LongVarChar: "string", parser.LineString: "string", parser.MultiLineString: "string", parser.Binary: "string", parser.VarBinary: "string", parser.TinyText: "string", parser.Text: "string", parser.MediumText: "string", parser.LongText: "string", parser.Enum: "string", parser.Set: "string", parser.Json: "string", parser.Blob: "string", parser.LongBlob: "string", parser.MediumBlob: "string", parser.TinyBlob: "string", // bool parser.Bool: "bool", parser.Boolean: "bool", } var commonMysqlDataTypeMap = map[int]string{ // number parser.Bit: "bit", parser.TinyInt: "tinyint", parser.SmallInt: "smallint", parser.MediumInt: "mediumint", parser.Int: "int", parser.MiddleInt: "middleint", parser.Int1: "int1", parser.Int2: "int2", parser.Int3: "int3", parser.Int4: "int4", parser.Int8: "int8", parser.Integer: "integer", parser.BigInt: "bigint", parser.Float: "float", parser.Float4: "float4", parser.Float8: "float8", parser.Double: "double", parser.Decimal: "decimal", parser.Dec: "dec", parser.Fixed: "fixed", parser.Numeric: "numeric", parser.Real: "real", // date&time parser.Date: "date", parser.DateTime: "datetime", parser.Timestamp: "timestamp", parser.Time: "time", parser.Year: "year", // string parser.Char: "char", parser.VarChar: "varchar", parser.NVarChar: "nvarchar", parser.NChar: "nchar", parser.Character: "character", parser.LongVarChar: "longvarchar", parser.LineString: "linestring", parser.MultiLineString: "multilinestring", parser.Binary: "binary", parser.VarBinary: "varbinary", parser.TinyText: "tinytext", parser.Text: "text", parser.MediumText: "mediumtext", parser.LongText: "longtext", parser.Enum: "enum", parser.Set: "set", parser.Json: "json", parser.Blob: "blob", parser.LongBlob: "longblob", parser.MediumBlob: "mediumblob", parser.TinyBlob: "tinyblob", // bool parser.Bool: "bool", parser.Boolean: "boolean", } var commonMysqlDataTypeMapString = map[string]string{ // For consistency, all integer types are converted to int64 // bool "bool": "bool", "_bool": "pq.BoolArray", "boolean": "bool", // number "tinyint": "int64", "smallint": "int64", "mediumint": "int64", "int": "int64", "int1": "int64", "int2": "int64", "_int2": "pq.Int64Array", "int3": "int64", "int4": "int64", "_int4": "pq.Int64Array", "int8": "int64", "_int8": "pq.Int64Array", "integer": "int64", "_integer": "pq.Int64Array", "bigint": "int64", "float": "float64", "float4": "float64", "_float4": "pq.Float64Array", "float8": "float64", "_float8": "pq.Float64Array", "double": "float64", "decimal": "float64", "dec": "float64", "fixed": "float64", "real": "float64", "bit": "byte", // date & time "date": "time.Time", "datetime": "time.Time", "timestamp": "time.Time", "time": "string", "year": "int64", // string "linestring": "string", "multilinestring": "string", "nvarchar": "string", "nchar": "string", "char": "string", "bpchar": "string", "_char": "pq.StringArray", "character": "string", "varchar": "string", "_varchar": "pq.StringArray", "binary": "string", "bytea": "string", "longvarbinary": "string", "varbinary": "string", "tinytext": "string", "text": "string", "_text": "pq.StringArray", "mediumtext": "string", "longtext": "string", "enum": "string", "set": "string", "json": "string", "jsonb": "string", "blob": "string", "longblob": "string", "mediumblob": "string", "tinyblob": "string", "ltree": "[]byte", } // ConvertDataType converts mysql column type into golang type func ConvertDataType(dataBaseType int, isDefaultNull, unsigned, strict bool) (string, string, error) { if env.UseExperimental() { tp, ok := commonMysqlDataTypeMap[dataBaseType] if !ok { return "", "", fmt.Errorf("unsupported database type: %v", dataBaseType) } goType, thirdPkg, _, err := ConvertStringDataType(tp, isDefaultNull, unsigned, strict) return goType, thirdPkg, err } // the following are the old version compatibility code. tp, ok := commonMysqlDataTypeMapInt[dataBaseType] if !ok { return "", "", fmt.Errorf("unsupported database type: %v", dataBaseType) } return mayConvertNullType(tp, isDefaultNull, unsigned, strict), "", nil } // ConvertStringDataType converts mysql column type into golang type func ConvertStringDataType(dataBaseType string, isDefaultNull, unsigned, strict bool) ( goType string, thirdPkg string, isPQArray bool, err error) { if env.UseExperimental() { customTp, thirdImport := convertDatatypeWithConfig(dataBaseType, isDefaultNull, unsigned) if len(customTp) != 0 { return customTp, thirdImport, false, nil } tp, ok := commonMysqlDataTypeMapString[strings.ToLower(dataBaseType)] if !ok { return "", "", false, fmt.Errorf("unsupported database type: %s", dataBaseType) } if strings.HasPrefix(dataBaseType, "_") { return tp, "", true, nil } return mayConvertNullType(tp, isDefaultNull, unsigned, strict), "", false, nil } // the following are the old version compatibility code. tp, ok := commonMysqlDataTypeMapString[strings.ToLower(dataBaseType)] if !ok { return "", "", false, fmt.Errorf("unsupported database type: %s", dataBaseType) } if strings.HasPrefix(dataBaseType, "_") { return tp, "", true, nil } return mayConvertNullType(tp, isDefaultNull, unsigned, strict), "", false, nil } func convertDatatypeWithConfig(dataBaseType string, isDefaultNull, unsigned bool) (string, string) { externalConfig, err := config.GetExternalConfig() if err != nil { return "", "" } opt, ok := externalConfig.Model.TypesMap[strings.ToLower(dataBaseType)] if !ok || (len(opt.Type) == 0 && len(opt.UnsignedType) == 0 && len(opt.NullType) == 0) { return "", "" } if isDefaultNull { if len(opt.NullType) != 0 { return opt.NullType, opt.Pkg } } else if unsigned { if len(opt.UnsignedType) != 0 { return opt.UnsignedType, opt.Pkg } } return opt.Type, opt.Pkg } func mayConvertNullType(goDataType string, isDefaultNull, unsigned, strict bool) string { if !isDefaultNull { if unsigned && strict { ret, ok := unsignedTypeMap[goDataType] if ok { return ret } } return goDataType } switch goDataType { case "int64": return "sql.NullInt64" case "int32": return "sql.NullInt32" case "float64": return "sql.NullFloat64" case "bool": return "sql.NullBool" case "string": return "sql.NullString" case "time.Time": return "sql.NullTime" default: if unsigned { ret, ok := unsignedTypeMap[goDataType] if ok { return ret } } return goDataType } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/model/sql/template/template.go
tools/goctl/model/sql/template/template.go
package template import ( _ "embed" "fmt" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util" ) // Customized defines a template for customized in model // //go:embed tpl/customized.tpl var Customized string // Vars defines a template for var block in model // //go:embed tpl/var.tpl var Vars string // Types defines a template for types in model. // //go:embed tpl/types.tpl var Types string // Tag defines a tag template text // //go:embed tpl/tag.tpl var Tag string // TableName defines a template that generate the tableName method. // //go:embed tpl/table-name.tpl var TableName string // New defines the template for creating model instance. // //go:embed tpl/model-new.tpl var New string // ModelCustom defines a template for extension // //go:embed tpl/model.tpl var ModelCustom string // ModelGen defines a template for model var ModelGen = fmt.Sprintf(`%s // versions: // goctl version: %s package {{.pkg}} {{.imports}} {{.vars}} {{.types}} {{.new}} {{.delete}} {{.find}} {{.insert}} {{.update}} {{.extraMethod}} {{.tableName}} {{.customized}} `, util.DoNotEditHead, version.BuildVersion) // Insert defines a template for insert code in model // //go:embed tpl/insert.tpl var Insert string // InsertMethod defines an interface method template for insert code in model // //go:embed tpl/interface-insert.tpl var InsertMethod string // Update defines a template for generating update codes // //go:embed tpl/update.tpl var Update string // UpdateMethod defines an interface method template for generating update codes // //go:embed tpl/interface-update.tpl var UpdateMethod string // Imports defines a import template for model in cache case // //go:embed tpl/import.tpl var Imports string // ImportsNoCache defines a import template for model in normal case // //go:embed tpl/import-no-cache.tpl var ImportsNoCache string // FindOne defines find row by id. // //go:embed tpl/find-one.tpl var FindOne string // FindOneByField defines find row by field. // //go:embed tpl/find-one-by-field.tpl var FindOneByField string // FindOneByFieldExtraMethod defines find row by field with extras. // //go:embed tpl/find-one-by-field-extra-method.tpl var FindOneByFieldExtraMethod string // FindOneMethod defines find row method. // //go:embed tpl/interface-find-one.tpl var FindOneMethod string // FindOneByFieldMethod defines find row by field method. // //go:embed tpl/interface-find-one-by-field.tpl var FindOneByFieldMethod string // Field defines a filed template for types // //go:embed tpl/field.tpl var Field string // Error defines an error template // //go:embed tpl/err.tpl var Error string // Delete defines a delete template // //go:embed tpl/delete.tpl var Delete string // DeleteMethod defines a delete template for interface method // //go:embed tpl/interface-delete.tpl var DeleteMethod string
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/model/sql/parser/parser.go
tools/goctl/model/sql/parser/parser.go
package parser import ( "fmt" "path/filepath" "sort" "strings" "github.com/zeromicro/ddl-parser/parser" "github.com/zeromicro/go-zero/core/collection" "github.com/zeromicro/go-zero/tools/goctl/model/sql/converter" "github.com/zeromicro/go-zero/tools/goctl/model/sql/model" "github.com/zeromicro/go-zero/tools/goctl/model/sql/util" "github.com/zeromicro/go-zero/tools/goctl/util/console" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) const timeImport = "time.Time" type ( // Table describes a mysql table Table struct { Name stringx.String Db stringx.String PrimaryKey Primary UniqueIndex map[string][]*Field Fields []*Field ContainsPQ bool } // Primary describes a primary key Primary struct { Field AutoIncrement bool } // Field describes a table field Field struct { NameOriginal string Name stringx.String ThirdPkg string DataType string Comment string SeqInIndex int OrdinalPosition int ContainsPQ bool } // KeyType types alias of int KeyType int ) func parseNameOriginal(ts []*parser.Table) (nameOriginals [][]string) { var columns []string for _, t := range ts { columns = []string{} for _, c := range t.Columns { columns = append(columns, c.Name) } nameOriginals = append(nameOriginals, columns) } return } // Parse parses ddl into golang structure func Parse(filename, database string, strict bool) ([]*Table, error) { p := parser.NewParser() tables, err := p.From(filename) if err != nil { return nil, err } nameOriginals := parseNameOriginal(tables) indexNameGen := func(column ...string) string { return strings.Join(column, "_") } prefix := filepath.Base(filename) var list []*Table for indexTable, e := range tables { var ( primaryColumn string primaryColumnSet = collection.NewSet[string]() uniqueKeyMap = make(map[string][]string) // Unused local variable // normalKeyMap = make(map[string][]string) columns = e.Columns ) for _, column := range columns { if column.Constraint != nil { if column.Constraint.Primary { primaryColumnSet.Add(column.Name) } if column.Constraint.Unique { indexName := indexNameGen(column.Name, "unique") uniqueKeyMap[indexName] = []string{column.Name} } if column.Constraint.Key { indexName := indexNameGen(column.Name, "idx") uniqueKeyMap[indexName] = []string{column.Name} } } } for _, e := range e.Constraints { if len(e.ColumnPrimaryKey) > 1 { return nil, fmt.Errorf("%s: unexpected join primary key", prefix) } if len(e.ColumnPrimaryKey) == 1 { primaryColumn = e.ColumnPrimaryKey[0] primaryColumnSet.Add(e.ColumnPrimaryKey[0]) } if len(e.ColumnUniqueKey) > 0 { list := append([]string(nil), e.ColumnUniqueKey...) list = append(list, "unique") indexName := indexNameGen(list...) uniqueKeyMap[indexName] = e.ColumnUniqueKey } } if primaryColumnSet.Count() > 1 { return nil, fmt.Errorf("%s: unexpected join primary key", prefix) } delete(uniqueKeyMap, indexNameGen(primaryColumn, "idx")) delete(uniqueKeyMap, indexNameGen(primaryColumn, "unique")) primaryKey, fieldM, err := convertColumns(columns, primaryColumn, strict) if err != nil { return nil, err } var fields []*Field // sort for indexColumn, c := range columns { field, ok := fieldM[c.Name] if ok { field.NameOriginal = nameOriginals[indexTable][indexColumn] fields = append(fields, field) } } uniqueIndex := make(map[string][]*Field) for indexName, each := range uniqueKeyMap { for _, columnName := range each { // Prevent a crash if there is a unique key constraint with a nil field. if fieldM[columnName] == nil { return nil, fmt.Errorf("table %s: unique key with error column name[%s]", e.Name, columnName) } uniqueIndex[indexName] = append(uniqueIndex[indexName], fieldM[columnName]) } } checkDuplicateUniqueIndex(uniqueIndex, e.Name) list = append(list, &Table{ Name: stringx.From(e.Name), Db: stringx.From(database), PrimaryKey: primaryKey, UniqueIndex: uniqueIndex, Fields: fields, }) } return list, nil } func checkDuplicateUniqueIndex(uniqueIndex map[string][]*Field, tableName string) { log := console.NewColorConsole() uniqueSet := collection.NewSet[string]() for k, i := range uniqueIndex { var list []string for _, e := range i { list = append(list, e.Name.Source()) } joinRet := strings.Join(list, ",") if uniqueSet.Contains(joinRet) { log.Warning("[checkDuplicateUniqueIndex]: table %s: duplicate unique index %s", tableName, joinRet) delete(uniqueIndex, k) continue } uniqueSet.Add(joinRet) } } func convertColumns(columns []*parser.Column, primaryColumn string, strict bool) (Primary, map[string]*Field, error) { var ( primaryKey Primary fieldM = make(map[string]*Field) log = console.NewColorConsole() ) for _, column := range columns { if column == nil { continue } var ( comment string isDefaultNull bool ) if column.Constraint != nil { comment = column.Constraint.Comment isDefaultNull = !column.Constraint.NotNull if !column.Constraint.NotNull && column.Constraint.HasDefaultValue { isDefaultNull = false } if column.Name == primaryColumn { isDefaultNull = false } } dataType, thirdPkg, err := converter.ConvertDataType(column.DataType.Type(), isDefaultNull, column.DataType.Unsigned(), strict) if err != nil { return Primary{}, nil, err } if column.Constraint != nil { if column.Name == primaryColumn { if !column.Constraint.AutoIncrement && dataType == "int64" { log.Warning("[convertColumns]: The primary key %q is recommended to add constraint `AUTO_INCREMENT`", column.Name) } } else if column.Constraint.NotNull && !column.Constraint.HasDefaultValue { log.Warning("[convertColumns]: The column %q is recommended to add constraint `DEFAULT`", column.Name) } } var field Field field.Name = stringx.From(column.Name) field.ThirdPkg = thirdPkg field.DataType = dataType field.Comment = util.TrimNewLine(comment) if field.Name.Source() == primaryColumn { primaryKey = Primary{ Field: field, } if column.Constraint != nil { primaryKey.AutoIncrement = column.Constraint.AutoIncrement } } fieldM[field.Name.Source()] = &field } return primaryKey, fieldM, nil } // ContainsTime returns true if contains golang type time.Time func (t *Table) ContainsTime() bool { for _, item := range t.Fields { if item.DataType == timeImport { return true } } return false } // ConvertDataType converts mysql data type into golang data type func ConvertDataType(table *model.Table, strict bool) (*Table, error) { isPrimaryDefaultNull := table.PrimaryKey.ColumnDefault == nil && table.PrimaryKey.IsNullAble == "YES" isPrimaryUnsigned := strings.Contains(table.PrimaryKey.DbColumn.ColumnType, "unsigned") primaryDataType, thirdPkg, containsPQ, err := converter.ConvertStringDataType(table.PrimaryKey.DataType, isPrimaryDefaultNull, isPrimaryUnsigned, strict) if err != nil { return nil, err } var reply Table reply.ContainsPQ = containsPQ reply.UniqueIndex = map[string][]*Field{} reply.Name = stringx.From(table.Table) reply.Db = stringx.From(table.Db) seqInIndex := 0 if table.PrimaryKey.Index != nil { seqInIndex = table.PrimaryKey.Index.SeqInIndex } reply.PrimaryKey = Primary{ Field: Field{ Name: stringx.From(table.PrimaryKey.Name), ThirdPkg: thirdPkg, DataType: primaryDataType, Comment: table.PrimaryKey.Comment, SeqInIndex: seqInIndex, OrdinalPosition: table.PrimaryKey.OrdinalPosition, }, AutoIncrement: strings.Contains(table.PrimaryKey.Extra, "auto_increment"), } fieldM, err := getTableFields(table, strict) if err != nil { return nil, err } for _, each := range fieldM { if each.ContainsPQ { reply.ContainsPQ = true } reply.Fields = append(reply.Fields, each) } sort.Slice(reply.Fields, func(i, j int) bool { return reply.Fields[i].OrdinalPosition < reply.Fields[j].OrdinalPosition }) uniqueIndexSet := collection.NewSet[string]() log := console.NewColorConsole() for indexName, each := range table.UniqueIndex { sort.Slice(each, func(i, j int) bool { if each[i].Index != nil { return each[i].Index.SeqInIndex < each[j].Index.SeqInIndex } return false }) if len(each) == 1 { one := each[0] if one.Name == table.PrimaryKey.Name { log.Warning("[ConvertDataType]: table %q, duplicate unique index with primary key: %q", table.Table, one.Name) continue } } var list []*Field var uniqueJoin []string for _, c := range each { list = append(list, fieldM[c.Name]) uniqueJoin = append(uniqueJoin, c.Name) } uniqueKey := strings.Join(uniqueJoin, ",") if uniqueIndexSet.Contains(uniqueKey) { log.Warning("[ConvertDataType]: table %q, duplicate unique index %q", table.Table, uniqueKey) continue } uniqueIndexSet.Add(uniqueKey) reply.UniqueIndex[indexName] = list } return &reply, nil } func getTableFields(table *model.Table, strict bool) (map[string]*Field, error) { fieldM := make(map[string]*Field) for _, each := range table.Columns { isDefaultNull := each.ColumnDefault == nil && each.IsNullAble == "YES" isPrimaryUnsigned := strings.Contains(each.ColumnType, "unsigned") dt, thirdPkg, containsPQ, err := converter.ConvertStringDataType(each.DataType, isDefaultNull, isPrimaryUnsigned, strict) if err != nil { return nil, err } columnSeqInIndex := 0 if each.Index != nil { columnSeqInIndex = each.Index.SeqInIndex } field := &Field{ NameOriginal: each.Name, Name: stringx.From(each.Name), ThirdPkg: thirdPkg, DataType: dt, Comment: each.Comment, SeqInIndex: columnSeqInIndex, OrdinalPosition: each.OrdinalPosition, ContainsPQ: containsPQ, } fieldM[each.Name] = field } return fieldM, nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/model/sql/parser/parser_test.go
tools/goctl/model/sql/parser/parser_test.go
package parser import ( _ "embed" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/model/sql/model" "github.com/zeromicro/go-zero/tools/goctl/model/sql/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) func TestParsePlainText(t *testing.T) { sqlFile := filepath.Join(pathx.MustTempDir(), "tmp.sql") err := os.WriteFile(sqlFile, []byte("plain text"), 0o777) assert.Nil(t, err) _, err = Parse(sqlFile, "go_zero", false) assert.NotNil(t, err) } func TestParseSelect(t *testing.T) { sqlFile := filepath.Join(pathx.MustTempDir(), "tmp.sql") err := os.WriteFile(sqlFile, []byte("select * from user"), 0o777) assert.Nil(t, err) tables, err := Parse(sqlFile, "go_zero", false) assert.Nil(t, err) assert.Equal(t, 0, len(tables)) } //go:embed testdata/user.sql var user string func TestParseCreateTable(t *testing.T) { sqlFile := filepath.Join(pathx.MustTempDir(), "tmp.sql") err := os.WriteFile(sqlFile, []byte(user), 0o777) assert.Nil(t, err) tables, err := Parse(sqlFile, "go_zero", false) assert.Equal(t, 1, len(tables)) table := tables[0] assert.Nil(t, err) assert.Equal(t, "test_user", table.Name.Source()) assert.Equal(t, "id", table.PrimaryKey.Name.Source()) assert.Equal(t, true, table.ContainsTime()) assert.Equal(t, 2, len(table.UniqueIndex)) assert.True(t, func() bool { for _, e := range table.Fields { if e.Comment != util.TrimNewLine(e.Comment) { return false } } return true }()) } func TestConvertColumn(t *testing.T) { t.Run("missingPrimaryKey", func(t *testing.T) { columnData := model.ColumnData{ Db: "user", Table: "user", Columns: []*model.Column{ { DbColumn: &model.DbColumn{ Name: "id", DataType: "bigint", }, }, }, } _, err := columnData.Convert() assert.NotNil(t, err) assert.Contains(t, err.Error(), "missing primary key") }) t.Run("jointPrimaryKey", func(t *testing.T) { columnData := model.ColumnData{ Db: "user", Table: "user", Columns: []*model.Column{ { DbColumn: &model.DbColumn{ Name: "id", DataType: "bigint", }, Index: &model.DbIndex{ IndexName: "PRIMARY", }, }, { DbColumn: &model.DbColumn{ Name: "mobile", DataType: "varchar", Comment: "手机号", }, Index: &model.DbIndex{ IndexName: "PRIMARY", }, }, }, } _, err := columnData.Convert() assert.NotNil(t, err) assert.Contains(t, err.Error(), "joint primary key is not supported") }) t.Run("normal", func(t *testing.T) { columnData := model.ColumnData{ Db: "user", Table: "user", Columns: []*model.Column{ { DbColumn: &model.DbColumn{ Name: "id", DataType: "bigint", Extra: "auto_increment", }, Index: &model.DbIndex{ IndexName: "PRIMARY", SeqInIndex: 1, }, }, { DbColumn: &model.DbColumn{ Name: "mobile", DataType: "varchar", Comment: "手机号", }, Index: &model.DbIndex{ IndexName: "mobile_unique", SeqInIndex: 1, }, }, }, } table, err := columnData.Convert() assert.Nil(t, err) assert.True(t, table.PrimaryKey.Index.IndexName == "PRIMARY" && table.PrimaryKey.Name == "id") for _, item := range table.Columns { if item.Name == "mobile" { assert.True(t, item.Index.NonUnique == 0) break } } }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/cmd.go
tools/goctl/rpc/cmd.go
package rpc import ( "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax" "github.com/zeromicro/go-zero/tools/goctl/rpc/cli" ) var ( // Cmd describes a rpc command. Cmd = cobrax.NewCommand("rpc", cobrax.WithRunE(func(command *cobra.Command, strings []string) error { return cli.RPCTemplate(true) })) templateCmd = cobrax.NewCommand("template", cobrax.WithRunE(func(command *cobra.Command, strings []string) error { return cli.RPCTemplate(false) })) newCmd = cobrax.NewCommand("new", cobrax.WithRunE(cli.RPCNew), cobrax.WithArgs(cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs))) protocCmd = cobrax.NewCommand("protoc", cobrax.WithRunE(cli.ZRPC), cobrax.WithArgs(cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs))) ) func init() { var ( rpcCmdFlags = Cmd.Flags() newCmdFlags = newCmd.Flags() protocCmdFlags = protocCmd.Flags() templateCmdFlags = templateCmd.Flags() ) rpcCmdFlags.StringVar(&cli.VarStringOutput, "o") rpcCmdFlags.StringVar(&cli.VarStringHome, "home") rpcCmdFlags.StringVar(&cli.VarStringRemote, "remote") rpcCmdFlags.StringVar(&cli.VarStringBranch, "branch") newCmdFlags.StringSliceVar(&cli.VarStringSliceGoOpt, "go_opt") newCmdFlags.StringSliceVar(&cli.VarStringSliceGoGRPCOpt, "go-grpc_opt") newCmdFlags.StringVarWithDefaultValue(&cli.VarStringStyle, "style", config.DefaultFormat) newCmdFlags.BoolVar(&cli.VarBoolIdea, "idea") newCmdFlags.StringVar(&cli.VarStringHome, "home") newCmdFlags.StringVar(&cli.VarStringRemote, "remote") newCmdFlags.StringVar(&cli.VarStringBranch, "branch") newCmdFlags.StringVar(&cli.VarStringModule, "module") newCmdFlags.BoolVarP(&cli.VarBoolVerbose, "verbose", "v") newCmdFlags.MarkHidden("go_opt") newCmdFlags.MarkHidden("go-grpc_opt") newCmdFlags.BoolVarPWithDefaultValue(&cli.VarBoolClient, "client", "c", true) protocCmdFlags.BoolVarP(&cli.VarBoolMultiple, "multiple", "m") protocCmdFlags.StringSliceVar(&cli.VarStringSliceGoOut, "go_out") protocCmdFlags.StringSliceVar(&cli.VarStringSliceGoGRPCOut, "go-grpc_out") protocCmdFlags.StringSliceVar(&cli.VarStringSliceGoOpt, "go_opt") protocCmdFlags.StringSliceVar(&cli.VarStringSliceGoGRPCOpt, "go-grpc_opt") protocCmdFlags.StringSliceVar(&cli.VarStringSlicePlugin, "plugin") protocCmdFlags.StringSliceVarP(&cli.VarStringSliceProtoPath, "proto_path", "I") protocCmdFlags.StringVar(&cli.VarStringStyle, "style") protocCmdFlags.StringVar(&cli.VarStringZRPCOut, "zrpc_out") protocCmdFlags.StringVar(&cli.VarStringHome, "home") protocCmdFlags.StringVar(&cli.VarStringRemote, "remote") protocCmdFlags.StringVar(&cli.VarStringBranch, "branch") protocCmdFlags.StringVar(&cli.VarStringModule, "module") protocCmdFlags.BoolVarP(&cli.VarBoolVerbose, "verbose", "v") protocCmdFlags.MarkHidden("go_out") protocCmdFlags.MarkHidden("go-grpc_out") protocCmdFlags.MarkHidden("go_opt") protocCmdFlags.MarkHidden("go-grpc_opt") protocCmdFlags.MarkHidden("plugin") protocCmdFlags.MarkHidden("proto_path") protocCmdFlags.BoolVarPWithDefaultValue(&cli.VarBoolClient, "client", "c", true) templateCmdFlags.StringVar(&cli.VarStringOutput, "o") templateCmdFlags.StringVar(&cli.VarStringHome, "home") templateCmdFlags.StringVar(&cli.VarStringRemote, "remote") templateCmdFlags.StringVar(&cli.VarStringBranch, "branch") Cmd.AddCommand(newCmd, protocCmd, templateCmd) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/execx/execx.go
tools/goctl/rpc/execx/execx.go
package execx import ( "bytes" "errors" "fmt" "os/exec" "runtime" "strings" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/vars" ) // RunFunc defines a function type of Run function type RunFunc func(string, string, ...*bytes.Buffer) (string, error) // Run provides the execution of shell scripts in golang, // which can support macOS, Windows, and Linux operating systems. // Other operating systems are currently not supported func Run(arg, dir string, in ...*bytes.Buffer) (string, error) { goos := runtime.GOOS var cmd *exec.Cmd switch goos { case vars.OsMac, vars.OsLinux: cmd = exec.Command("sh", "-c", arg) case vars.OsWindows: cmd = exec.Command("cmd.exe", "/c", arg) default: return "", fmt.Errorf("unexpected os: %v", goos) } if len(dir) > 0 { cmd.Dir = dir } stdout := new(bytes.Buffer) stderr := new(bytes.Buffer) if len(in) > 0 { cmd.Stdin = in[0] } cmd.Stdout = stdout cmd.Stderr = stderr err := cmd.Run() if err != nil { if stderr.Len() > 0 { return "", errors.New(strings.TrimSuffix(stderr.String(), pathx.NL)) } return "", err } return strings.TrimSuffix(stdout.String(), pathx.NL), nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genserver.go
tools/goctl/rpc/generator/genserver.go
package generator import ( _ "embed" "fmt" "path/filepath" "strings" "github.com/zeromicro/go-zero/core/collection" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) const functionTemplate = ` {{if .hasComment}}{{.comment}}{{end}} func (s *{{.server}}Server) {{.method}} ({{if .notStream}}ctx context.Context,{{if .hasReq}} in {{.request}}{{end}}{{else}}{{if .hasReq}} in {{.request}},{{end}}stream {{.streamBody}}{{end}}) ({{if .notStream}}{{.response}},{{end}}error) { l := {{.logicPkg}}.New{{.logicName}}({{if .notStream}}ctx,{{else}}stream.Context(),{{end}}s.svcCtx) return l.{{.method}}({{if .hasReq}}in{{if .stream}} ,stream{{end}}{{else}}{{if .stream}}stream{{end}}{{end}}) } ` //go:embed server.tpl var serverTemplate string // GenServer generates rpc server file, which is an implementation of rpc server func (g *Generator) GenServer(ctx DirContext, proto parser.Proto, cfg *conf.Config, c *ZRpcContext) error { if !c.Multiple { return g.genServerInCompatibility(ctx, proto, cfg, c) } return g.genServerGroup(ctx, proto, cfg) } func (g *Generator) genServerGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { dir := ctx.GetServer() for _, service := range proto.Service { var ( serverFile string logicImport string ) serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") if err != nil { return err } serverChildPkg, err := dir.GetChildPackage(service.Name) if err != nil { return err } logicChildPkg, err := ctx.GetLogic().GetChildPackage(service.Name) if err != nil { return err } serverDir := filepath.Base(serverChildPkg) logicImport = fmt.Sprintf(`"%v"`, logicChildPkg) serverFile = filepath.Join(dir.Filename, serverDir, serverFilename+".go") svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package) pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package) imports := collection.NewSet[string]() imports.Add(logicImport, svcImport, pbImport) head := util.GetHead(proto.Name) funcList, err := g.genFunctions(proto.PbPackage, service, true) if err != nil { return err } text, err := pathx.LoadTemplate(category, serverTemplateFile, serverTemplate) if err != nil { return err } notStream := false for _, rpc := range service.RPC { if !rpc.StreamsRequest && !rpc.StreamsReturns { notStream = true break } } if err = util.With("server").GoFmt(true).Parse(text).SaveTo(map[string]any{ "head": head, "unimplementedServer": fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, parser.CamelCase(service.Name)), "server": stringx.From(service.Name).ToCamel(), "imports": strings.Join(imports.Keys(), pathx.NL), "funcs": strings.Join(funcList, pathx.NL), "notStream": notStream, }, serverFile, true); err != nil { return err } } return nil } func (g *Generator) genServerInCompatibility(ctx DirContext, proto parser.Proto, cfg *conf.Config, c *ZRpcContext) error { dir := ctx.GetServer() logicImport := fmt.Sprintf(`"%v"`, ctx.GetLogic().Package) svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package) pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package) imports := collection.NewSet[string]() imports.Add(logicImport, svcImport, pbImport) head := util.GetHead(proto.Name) service := proto.Service[0] serverFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name+"_server") if err != nil { return err } serverFile := filepath.Join(dir.Filename, serverFilename+".go") funcList, err := g.genFunctions(proto.PbPackage, service, false) if err != nil { return err } text, err := pathx.LoadTemplate(category, serverTemplateFile, serverTemplate) if err != nil { return err } notStream := false for _, rpc := range service.RPC { if !rpc.StreamsRequest && !rpc.StreamsReturns { notStream = true break } } return util.With("server").GoFmt(true).Parse(text).SaveTo(map[string]any{ "head": head, "unimplementedServer": fmt.Sprintf("%s.Unimplemented%sServer", proto.PbPackage, parser.CamelCase(service.Name)), "server": stringx.From(service.Name).ToCamel(), "imports": strings.Join(imports.Keys(), pathx.NL), "funcs": strings.Join(funcList, pathx.NL), "notStream": notStream, }, serverFile, true) } func (g *Generator) genFunctions(goPackage string, service parser.Service, multiple bool) ([]string, error) { var ( functionList []string logicPkg string ) for _, rpc := range service.RPC { text, err := pathx.LoadTemplate(category, serverFuncTemplateFile, functionTemplate) if err != nil { return nil, err } var logicName string if !multiple { logicPkg = "logic" logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) } else { nameJoin := fmt.Sprintf("%s_logic", service.Name) logicPkg = strings.ToLower(stringx.From(nameJoin).ToCamel()) logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) } comment := parser.GetComment(rpc.Doc()) streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Server") buffer, err := util.With("func").Parse(text).Execute(map[string]any{ "server": stringx.From(service.Name).ToCamel(), "logicName": logicName, "method": parser.CamelCase(rpc.Name), "request": fmt.Sprintf("*%s.%s", goPackage, parser.CamelCase(rpc.RequestType)), "response": fmt.Sprintf("*%s.%s", goPackage, parser.CamelCase(rpc.ReturnsType)), "hasComment": len(comment) > 0, "comment": comment, "hasReq": !rpc.StreamsRequest, "stream": rpc.StreamsRequest || rpc.StreamsReturns, "notStream": !rpc.StreamsRequest && !rpc.StreamsReturns, "streamBody": streamServer, "logicPkg": logicPkg, }) if err != nil { return nil, err } functionList = append(functionList, buffer.String()) } return functionList, nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/prototmpl.go
tools/goctl/rpc/generator/prototmpl.go
package generator import ( _ "embed" "path/filepath" "strings" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) //go:embed rpc.tpl var rpcTemplateText string // ProtoTmpl returns a sample of a proto file func ProtoTmpl(out string) error { protoFilename := filepath.Base(out) serviceName := stringx.From(strings.TrimSuffix(protoFilename, filepath.Ext(protoFilename))) text, err := pathx.LoadTemplate(category, rpcTemplateFile, rpcTemplateText) if err != nil { return err } dir := filepath.Dir(out) err = pathx.MkdirIfNotExist(dir) if err != nil { return err } err = util.With("t").Parse(text).SaveTo(map[string]string{ "package": serviceName.Untitle(), "serviceName": serviceName.Title(), }, out, false) return err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genconfig.go
tools/goctl/rpc/generator/genconfig.go
package generator import ( _ "embed" "os" "path/filepath" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) //go:embed config.tpl var configTemplate string // GenConfig generates the configuration structure definition file of the rpc service, // which contains the zrpc.RpcServerConf configuration item by default. // You can specify the naming style of the target file name through config.Config. For details, // see https://github.com/zeromicro/go-zero/tree/master/tools/goctl/config/config.go func (g *Generator) GenConfig(ctx DirContext, _ parser.Proto, cfg *conf.Config) error { dir := ctx.GetConfig() configFilename, err := format.FileNamingFormat(cfg.NamingFormat, "config") if err != nil { return err } fileName := filepath.Join(dir.Filename, configFilename+".go") if pathx.FileExists(fileName) { return nil } text, err := pathx.LoadTemplate(category, configTemplateFileFile, configTemplate) if err != nil { return err } return os.WriteFile(fileName, []byte(text), os.ModePerm) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genpb_test.go
tools/goctl/rpc/generator/genpb_test.go
package generator import ( "os" "os/exec" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) func Test_findPbFile(t *testing.T) { dir := t.TempDir() protoFile := filepath.Join(dir, "greet.proto") err := os.WriteFile(protoFile, []byte(` syntax = "proto3"; package greet; option go_package="./greet"; message Req{} message Resp{} service Greeter { rpc greet(Req) returns (Resp); } `), 0o666) if err != nil { t.Log(err) return } t.Run("", func(t *testing.T) { output := t.TempDir() grpc := filepath.Join(output, "grpc") err := pathx.MkdirIfNotExist(grpc) if err != nil { t.Log(err) return } cmd := exec.Command("protoc", "-I="+filepath.Dir(protoFile), "--go_out="+output, "--go-grpc_out="+grpc, filepath.Base(protoFile)) cmd.Dir = output cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { t.Log(err) return } pbDir, err := findPbFile(output, protoFile, false) assert.Nil(t, err) pbGo := filepath.Join(pbDir, "greet.pb.go") assert.True(t, pathx.FileExists(pbGo)) grpcDir, err := findPbFile(output, protoFile, true) assert.Nil(t, err) grpcGo := filepath.Join(grpcDir, "greet_grpc.pb.go") assert.True(t, pathx.FileExists(grpcGo)) }) t.Run("", func(t *testing.T) { output := t.TempDir() redirect := filepath.Join(output, "pb") grpc := filepath.Join(output, "grpc") err := pathx.MkdirIfNotExist(grpc) if err != nil { t.Log(err) return } cmd := exec.Command("protoc", "-I="+filepath.Dir(protoFile), "--go_out="+output, "--go-grpc_out="+grpc, filepath.Base(protoFile), "--go_opt=M"+filepath.Base(protoFile)+"="+redirect) cmd.Dir = output cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { t.Log(err) return } pbDir, err := findPbFile(output, protoFile, false) assert.Nil(t, err) pbGo := filepath.Join(pbDir, "greet.pb.go") assert.True(t, pathx.FileExists(pbGo)) grpcDir, err := findPbFile(output, protoFile, true) assert.Nil(t, err) grpcGo := filepath.Join(grpcDir, "greet_grpc.pb.go") assert.True(t, pathx.FileExists(grpcGo)) }) t.Run("", func(t *testing.T) { output := t.TempDir() pbeRedirect := filepath.Join(output, "redirect") grpc := filepath.Join(output, "grpc") grpcRedirect := filepath.Join(grpc, "redirect") err := pathx.MkdirIfNotExist(grpc) if err != nil { t.Log(err) return } cmd := exec.Command("protoc", "-I="+filepath.Dir(protoFile), "--go_out="+output, "--go-grpc_out="+grpc, filepath.Base(protoFile), "--go_opt=M"+filepath.Base(protoFile)+"="+pbeRedirect, "--go-grpc_opt=M"+filepath.Base(protoFile)+"="+grpcRedirect) cmd.Dir = output cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { t.Log(err) return } pbDir, err := findPbFile(output, protoFile, false) assert.Nil(t, err) pbGo := filepath.Join(pbDir, "greet.pb.go") assert.True(t, pathx.FileExists(pbGo)) grpcDir, err := findPbFile(output, protoFile, true) assert.Nil(t, err) grpcGo := filepath.Join(grpcDir, "greet_grpc.pb.go") assert.True(t, pathx.FileExists(grpcGo)) }) t.Run("", func(t *testing.T) { output := t.TempDir() pbeRedirect := filepath.Join(output, "redirect") grpc := filepath.Join(output, "grpc") grpcRedirect := filepath.Join(grpc, "redirect") err := pathx.MkdirIfNotExist(grpc) if err != nil { t.Log(err) return } cmd := exec.Command("protoc", "-I="+filepath.Dir(protoFile), "--go_out="+output, "--go-grpc_out="+grpc, filepath.Base(protoFile), "--go_opt=M"+filepath.Base(protoFile)+"="+pbeRedirect, "--go-grpc_opt=M"+filepath.Base(protoFile)+"="+grpcRedirect, "--go_opt=paths=import", "--go-grpc_opt=paths=source_relative") cmd.Dir = output cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { t.Log(err) return } pbDir, err := findPbFile(output, protoFile, false) assert.Nil(t, err) pbGo := filepath.Join(pbDir, "greet.pb.go") assert.True(t, pathx.FileExists(pbGo)) grpcDir, err := findPbFile(output, protoFile, true) assert.Nil(t, err) grpcGo := filepath.Join(grpcDir, "greet_grpc.pb.go") assert.True(t, pathx.FileExists(grpcGo)) }) t.Run("", func(t *testing.T) { output := t.TempDir() pbeRedirect := filepath.Join(output, "redirect") grpc := filepath.Join(output, "grpc") grpcRedirect := filepath.Join(grpc, "redirect") err := pathx.MkdirIfNotExist(grpc) if err != nil { t.Log(err) return } err = pathx.MkdirIfNotExist(pbeRedirect) if err != nil { t.Log(err) return } err = pathx.MkdirIfNotExist(grpcRedirect) if err != nil { t.Log(err) return } cmd := exec.Command("protoc", "-I="+filepath.Dir(protoFile), "--go_out="+output, "--go-grpc_out="+grpc, filepath.Base(protoFile), "--go_opt=M"+filepath.Base(protoFile)+"="+pbeRedirect, "--go-grpc_opt=M"+filepath.Base(protoFile)+"="+grpcRedirect, "--go_opt=paths=import", "--go-grpc_opt=paths=source_relative", "--go_out="+pbeRedirect, "--go-grpc_out="+grpcRedirect) cmd.Dir = output cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err = cmd.Run() if err != nil { t.Log(err) return } pbDir, err := findPbFile(output, protoFile, false) assert.Nil(t, err) pbGo := filepath.Join(pbDir, "greet.pb.go") assert.True(t, pathx.FileExists(pbGo)) grpcDir, err := findPbFile(output, protoFile, true) assert.Nil(t, err) grpcGo := filepath.Join(grpcDir, "greet_grpc.pb.go") assert.True(t, pathx.FileExists(grpcGo)) }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/gen_module_test.go
tools/goctl/rpc/generator/gen_module_test.go
package generator import ( "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestRpcGenerateWithModule(t *testing.T) { tests := []struct { name string moduleName string expectedMod string serviceName string }{ { name: "with custom module", moduleName: "github.com/test/customrpc", expectedMod: "github.com/test/customrpc", serviceName: "testrpc", }, { name: "with simple module", moduleName: "simplerpc", expectedMod: "simplerpc", serviceName: "testrpc", }, { name: "with empty module uses directory", moduleName: "", expectedMod: "testrpc", // Should use directory name serviceName: "testrpc", }, { name: "with domain module", moduleName: "example.com/user/rpcservice", expectedMod: "example.com/user/rpcservice", serviceName: "userrpc", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Create temporary directory tempDir, err := os.MkdirTemp("", "goctl-rpc-module-test-*") require.NoError(t, err) defer os.RemoveAll(tempDir) // Create service directory serviceDir := filepath.Join(tempDir, tt.serviceName) err = os.MkdirAll(serviceDir, 0755) require.NoError(t, err) // Create a simple proto file for testing protoContent := `syntax = "proto3"; package ` + tt.serviceName + `; option go_package = "./` + tt.serviceName + `"; message PingRequest { string ping = 1; } message PongResponse { string pong = 1; } service ` + strings.Title(tt.serviceName) + ` { rpc Ping(PingRequest) returns (PongResponse); } ` protoFile := filepath.Join(serviceDir, tt.serviceName+".proto") err = os.WriteFile(protoFile, []byte(protoContent), 0644) require.NoError(t, err) // Create the generator g := NewGenerator("go_zero", false) // Use non-verbose mode for tests // Set up ZRpcContext with module support zctx := &ZRpcContext{ Src: protoFile, ProtocCmd: "", // We'll skip protoc generation in tests GoOutput: serviceDir, GrpcOutput: serviceDir, Output: serviceDir, Multiple: false, IsGenClient: false, Module: tt.moduleName, } // Skip environment preparation and protoc generation for tests // We'll create minimal proto-generated files manually pbDir := filepath.Join(serviceDir, tt.serviceName) err = os.MkdirAll(pbDir, 0755) require.NoError(t, err) // Create minimal pb.go file pbContent := `package ` + tt.serviceName + ` type PingRequest struct { Ping string } type PongResponse struct { Pong string } ` pbFile := filepath.Join(pbDir, tt.serviceName+".pb.go") err = os.WriteFile(pbFile, []byte(pbContent), 0644) require.NoError(t, err) // Create minimal grpc pb file grpcContent := `package ` + tt.serviceName + ` import "context" type ` + strings.Title(tt.serviceName) + `Client interface { Ping(ctx context.Context, in *PingRequest) (*PongResponse, error) } type ` + strings.Title(tt.serviceName) + `Server interface { Ping(ctx context.Context, in *PingRequest) (*PongResponse, error) } ` grpcFile := filepath.Join(pbDir, tt.serviceName+"_grpc.pb.go") err = os.WriteFile(grpcFile, []byte(grpcContent), 0644) require.NoError(t, err) // Set the protoc directories to point to our manually created pb files zctx.ProtoGenGoDir = pbDir zctx.ProtoGenGrpcDir = pbDir // Now test the generation with module support // We need to test the core functionality without protoc err = testRpcGenerateCore(g, zctx) if err != nil { // If there are protoc-related errors, that's expected in test environment // The key is that module setup should work t.Logf("Expected protoc-related error: %v", err) } // Check that go.mod file was created with correct module name goModPath := filepath.Join(serviceDir, "go.mod") if _, err := os.Stat(goModPath); err == nil { content, err := os.ReadFile(goModPath) require.NoError(t, err) assert.Contains(t, string(content), "module "+tt.expectedMod) t.Logf("go.mod content: %s", string(content)) } // Check basic directory structure etcDir := filepath.Join(serviceDir, "etc") internalDir := filepath.Join(serviceDir, "internal") if _, err := os.Stat(etcDir); err == nil { assert.DirExists(t, etcDir) } if _, err := os.Stat(internalDir); err == nil { assert.DirExists(t, internalDir) } }) } } // testRpcGenerateCore tests the core generation logic without full protoc integration func testRpcGenerateCore(g *Generator, zctx *ZRpcContext) error { abs, err := filepath.Abs(zctx.Output) if err != nil { return err } // Test the context preparation with module if len(zctx.Module) > 0 { // This should work with our implemented PrepareWithModule _, err = filepath.Abs(abs) // Basic validation that path operations work if err != nil { return err } } return nil } func TestZRpcContext_ModuleField(t *testing.T) { // Test that ZRpcContext properly holds the Module field zctx := &ZRpcContext{ Src: "/path/to/test.proto", Output: "/path/to/output", Multiple: false, IsGenClient: false, Module: "github.com/test/module", } assert.Equal(t, "github.com/test/module", zctx.Module) assert.Equal(t, "/path/to/test.proto", zctx.Src) assert.Equal(t, "/path/to/output", zctx.Output) assert.False(t, zctx.Multiple) assert.False(t, zctx.IsGenClient) } func TestRpcModuleIntegration_BasicFunctionality(t *testing.T) { // Test that module name propagates correctly through the system tempDir, err := os.MkdirTemp("", "goctl-rpc-basic-test-*") require.NoError(t, err) defer os.RemoveAll(tempDir) serviceName := "basictest" serviceDir := filepath.Join(tempDir, serviceName) err = os.MkdirAll(serviceDir, 0755) require.NoError(t, err) // Test different module name formats moduleTests := []struct { name string module string valid bool }{ {"github module", "github.com/user/repo", true}, {"domain module", "example.com/project", true}, {"simple module", "mymodule", true}, {"versioned module", "github.com/user/repo/v2", true}, {"underscore module", "my_module", true}, {"hyphen module", "my-module", true}, {"empty module", "", true}, // Should use directory name } for _, mt := range moduleTests { t.Run(mt.name, func(t *testing.T) { zctx := &ZRpcContext{ Output: serviceDir, Module: mt.module, Multiple: false, } assert.Equal(t, mt.module, zctx.Module) // Basic validation that the structure supports modules assert.NotNil(t, zctx) if mt.module != "" { assert.Contains(t, mt.module, mt.module) // Tautology to ensure string is preserved } }) } } func TestRpcGenerator_ModuleSupport(t *testing.T) { // Test that the generator properly handles module names g := NewGenerator("go_zero", false) assert.NotNil(t, g) // Test that we can create ZRpcContext with modules testModules := []string{ "github.com/example/rpc", "simple", "domain.com/path/to/service", "", } for _, module := range testModules { zctx := &ZRpcContext{ Module: module, Output: "/tmp/test", Multiple: false, } assert.Equal(t, module, zctx.Module) // Verify the generator can accept this context assert.NotNil(t, g) assert.NotNil(t, zctx) // The actual Generate call would require protoc setup, // so we just verify the structure is correct } } func TestRandomProjectGeneration_WithModule(t *testing.T) { // Test with random project names like in the original test projectName := "testproj123" // Use fixed name for reproducible tests tempDir, err := os.MkdirTemp("", "goctl-rpc-random-test-*") require.NoError(t, err) defer os.RemoveAll(tempDir) serviceDir := filepath.Join(tempDir, projectName) err = os.MkdirAll(serviceDir, 0755) require.NoError(t, err) // Test with a custom module name customModule := "github.com/test/" + projectName zctx := &ZRpcContext{ Src: filepath.Join(serviceDir, "test.proto"), Output: serviceDir, Module: customModule, Multiple: false, IsGenClient: false, } assert.Equal(t, customModule, zctx.Module) assert.Contains(t, zctx.Module, projectName) // Create a basic proto file protoContent := `syntax = "proto3"; package test; option go_package = "./test"; message Request {} message Response {} service Test { rpc Call(Request) returns (Response); }` err = os.WriteFile(zctx.Src, []byte(protoContent), 0644) require.NoError(t, err) // Verify file was created and context is properly set assert.FileExists(t, zctx.Src) assert.Equal(t, customModule, zctx.Module) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genetc.go
tools/goctl/rpc/generator/genetc.go
package generator import ( _ "embed" "fmt" "path/filepath" "strings" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) //go:embed etc.tpl var etcTemplate string // GenEtc generates the yaml configuration file of the rpc service, // including host, port monitoring configuration items and etcd configuration func (g *Generator) GenEtc(ctx DirContext, _ parser.Proto, cfg *conf.Config) error { dir := ctx.GetEtc() etcFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source()) if err != nil { return err } fileName := filepath.Join(dir.Filename, fmt.Sprintf("%v.yaml", etcFilename)) text, err := pathx.LoadTemplate(category, etcTemplateFileFile, etcTemplate) if err != nil { return err } return util.With("etc").Parse(text).SaveTo(map[string]any{ "serviceName": strings.ToLower(stringx.From(ctx.GetServiceName().Source()).ToCamel()), }, fileName, false) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/gen.go
tools/goctl/rpc/generator/gen.go
package generator import ( "path/filepath" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util/console" "github.com/zeromicro/go-zero/tools/goctl/util/ctx" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) type ZRpcContext struct { // Src is the source file of the proto. Src string // ProtocCmd is the command to generate proto files. ProtocCmd string // ProtoGenGrpcDir is the directory to store the generated proto files. ProtoGenGrpcDir string // ProtoGenGoDir is the directory to store the generated go files. ProtoGenGoDir string // IsGooglePlugin is the flag to indicate whether the proto file is generated by google plugin. IsGooglePlugin bool // GoOutput is the output directory of the generated go files. GoOutput string // GrpcOutput is the output directory of the generated grpc files. GrpcOutput string // Output is the output directory of the generated files. Output string // Multiple is the flag to indicate whether the proto file is generated in multiple mode. Multiple bool // Whether to generate rpc client IsGenClient bool // Module is the custom module name for go.mod Module string } // Generate generates a rpc service, through the proto file, // code storage directory, and proto import parameters to control // the source file and target location of the rpc service that needs to be generated func (g *Generator) Generate(zctx *ZRpcContext) error { abs, err := filepath.Abs(zctx.Output) if err != nil { return err } err = pathx.MkdirIfNotExist(abs) if err != nil { return err } err = g.Prepare() if err != nil { return err } var projectCtx *ctx.ProjectContext if len(zctx.Module) > 0 { projectCtx, err = ctx.PrepareWithModule(abs, zctx.Module) } else { projectCtx, err = ctx.Prepare(abs) } if err != nil { return err } p := parser.NewDefaultProtoParser() proto, err := p.Parse(zctx.Src, zctx.Multiple) if err != nil { return err } dirCtx, err := mkdir(projectCtx, proto, g.cfg, zctx) if err != nil { return err } err = g.GenEtc(dirCtx, proto, g.cfg) if err != nil { return err } err = g.GenPb(dirCtx, zctx) if err != nil { return err } err = g.GenConfig(dirCtx, proto, g.cfg) if err != nil { return err } err = g.GenSvc(dirCtx, proto, g.cfg) if err != nil { return err } err = g.GenLogic(dirCtx, proto, g.cfg, zctx) if err != nil { return err } err = g.GenServer(dirCtx, proto, g.cfg, zctx) if err != nil { return err } err = g.GenMain(dirCtx, proto, g.cfg, zctx) if err != nil { return err } if zctx.IsGenClient { err = g.GenCall(dirCtx, proto, g.cfg, zctx) } console.NewColorConsole().MarkDone() return err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/prototmpl_test.go
tools/goctl/rpc/generator/prototmpl_test.go
package generator import ( "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) func TestProtoTmpl(t *testing.T) { _ = Clean() // exists dir err := ProtoTmpl(pathx.MustTempDir()) assert.Nil(t, err) // not exist dir dir := filepath.Join(pathx.MustTempDir(), "test") err = ProtoTmpl(dir) assert.Nil(t, err) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/gen_test.go
tools/goctl/rpc/generator/gen_test.go
package generator import ( "fmt" "go/build" "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/tools/goctl/rpc/execx" ) func TestRpcGenerate(t *testing.T) { _ = Clean() g := NewGenerator("gozero", true) err := g.Prepare() if err != nil { logx.Error(err) return } projectName := stringx.Rand() src := filepath.Join(build.Default.GOPATH, "src") _, err = os.Stat(src) if err != nil { return } projectDir := filepath.Join(src, projectName) srcDir := projectDir defer func() { _ = os.RemoveAll(srcDir) }() common, err := filepath.Abs(".") assert.Nil(t, err) // case go path t.Run("GOPATH", func(t *testing.T) { ctx := &ZRpcContext{ Src: "./test.proto", ProtocCmd: fmt.Sprintf("protoc -I=%s test.proto --go_out=%s --go_opt=Mbase/common.proto=./base --go-grpc_out=%s", common, projectDir, projectDir), IsGooglePlugin: true, GoOutput: projectDir, GrpcOutput: projectDir, Output: projectDir, } err = g.Generate(ctx) assert.Nil(t, err) _, err = execx.Run("go test "+projectName, projectDir) assert.Error(t, err) }) // case go mod t.Run("GOMOD", func(t *testing.T) { workDir := projectDir name := filepath.Base(projectDir) _, err = execx.Run("go mod init "+name, workDir) if err != nil { logx.Error(err) return } projectDir = filepath.Join(workDir, projectName) ctx := &ZRpcContext{ Src: "./test.proto", ProtocCmd: fmt.Sprintf("protoc -I=%s test.proto --go_out=%s --go_opt=Mbase/common.proto=./base --go-grpc_out=%s", common, projectDir, projectDir), IsGooglePlugin: true, GoOutput: projectDir, GrpcOutput: projectDir, Output: projectDir, } err = g.Generate(ctx) assert.Nil(t, err) }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genpb.go
tools/goctl/rpc/generator/genpb.go
package generator import ( "errors" "fmt" "io/fs" "os" "path/filepath" "strings" "github.com/zeromicro/go-zero/tools/goctl/rpc/execx" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) // GenPb generates the pb.go file, which is a layer of packaging for protoc to generate gprc, // but the commands and flags in protoc are not completely joined in goctl. At present, proto_path(-I) is introduced func (g *Generator) GenPb(ctx DirContext, c *ZRpcContext) error { return g.genPbDirect(ctx, c) } func (g *Generator) genPbDirect(ctx DirContext, c *ZRpcContext) error { g.log.Debug("[command]: %s", c.ProtocCmd) pwd, err := os.Getwd() if err != nil { return err } _, err = execx.Run(c.ProtocCmd, pwd) if err != nil { return err } return g.setPbDir(ctx, c) } func (g *Generator) setPbDir(ctx DirContext, c *ZRpcContext) error { pbDir, err := findPbFile(c.GoOutput, c.Src, false) if err != nil { return err } if len(pbDir) == 0 { return fmt.Errorf("pg.go is not found under %q", c.GoOutput) } grpcDir, err := findPbFile(c.GrpcOutput, c.Src, true) if err != nil { return err } if len(grpcDir) == 0 { return fmt.Errorf("_grpc.pb.go is not found in %q", c.GrpcOutput) } if pbDir != grpcDir { return fmt.Errorf("the pb.go and _grpc.pb.go must under the same dir: "+ "\n pb.go: %s\n_grpc.pb.go: %s", pbDir, grpcDir) } if pbDir == c.Output { return fmt.Errorf("the output of pb.go and _grpc.pb.go must not be the same "+ "with --zrpc_out:\npb output: %s\nzrpc out: %s", pbDir, c.Output) } ctx.SetPbDir(pbDir, grpcDir) return nil } const ( pbSuffix = "pb.go" grpcSuffix = "_grpc.pb.go" ) func findPbFile(current string, src string, grpc bool) (string, error) { protoName := strings.TrimSuffix(filepath.Base(src), filepath.Ext(src)) pbFile := protoName + "." + pbSuffix grpcFile := protoName + grpcSuffix fileSystem := os.DirFS(current) var ret string err := fs.WalkDir(fileSystem, ".", func(path string, d fs.DirEntry, err error) error { if d.IsDir() { return nil } if strings.HasSuffix(path, pbSuffix) { if grpc { if strings.HasSuffix(path, grpcFile) { ret = path return os.ErrExist } } else if strings.HasSuffix(path, pbFile) { ret = path return os.ErrExist } } return nil }) if errors.Is(err, os.ErrExist) { return pathx.ReadLink(filepath.Dir(filepath.Join(current, ret))) } return "", err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/gencall.go
tools/goctl/rpc/generator/gencall.go
package generator import ( _ "embed" "fmt" "path/filepath" "sort" "strings" "github.com/emicklei/proto" "github.com/zeromicro/go-zero/core/collection" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) const ( callInterfaceFunctionTemplate = `{{if .hasComment}}{{.comment}} {{end}}{{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error)` callFunctionTemplate = ` {{if .hasComment}}{{.comment}}{{end}} func (m *default{{.serviceName}}) {{.method}}(ctx context.Context{{if .hasReq}}, in *{{.pbRequest}}{{end}}, opts ...grpc.CallOption) ({{if .notStream}}*{{.pbResponse}}, {{else}}{{.streamBody}},{{end}} error) { client := {{if .isCallPkgSameToGrpcPkg}}{{else}}{{.package}}.{{end}}New{{.rpcServiceName}}Client(m.cli.Conn()) return client.{{.method}}(ctx{{if .hasReq}}, in{{end}}, opts...) } ` ) //go:embed call.tpl var callTemplateText string // GenCall generates the rpc client code, which is the entry point for the rpc service call. // It is a layer of encapsulation for the rpc client and shields the details in the pb. func (g *Generator) GenCall(ctx DirContext, proto parser.Proto, cfg *conf.Config, c *ZRpcContext) error { if !c.Multiple { return g.genCallInCompatibility(ctx, proto, cfg) } return g.genCallGroup(ctx, proto, cfg) } func (g *Generator) genCallGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { dir := ctx.GetCall() head := util.GetHead(proto.Name) for _, service := range proto.Service { childPkg, err := dir.GetChildPackage(service.Name) if err != nil { return err } callFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name) if err != nil { return err } childDir := filepath.Base(childPkg) filename := filepath.Join(dir.Filename, childDir, fmt.Sprintf("%s.go", callFilename)) isCallPkgSameToPbPkg := childDir == ctx.GetProtoGo().Filename isCallPkgSameToGrpcPkg := childDir == ctx.GetProtoGo().Filename serviceName := stringx.From(service.Name).ToCamel() alias := collection.NewSet[string]() var hasSameNameBetweenMessageAndService bool for _, item := range proto.Message { msgName := getMessageName(*item.Message) if serviceName == msgName { hasSameNameBetweenMessageAndService = true } if !isCallPkgSameToPbPkg { alias.Add(fmt.Sprintf("%s = %s", parser.CamelCase(msgName), fmt.Sprintf("%s.%s", proto.PbPackage, parser.CamelCase(msgName)))) } } if hasSameNameBetweenMessageAndService { serviceName = stringx.From(service.Name + "_zrpc_client").ToCamel() } functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg) if err != nil { return err } iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg) if err != nil { return err } text, err := pathx.LoadTemplate(category, callTemplateFile, callTemplateText) if err != nil { return err } pbPackage := fmt.Sprintf(`"%s"`, ctx.GetPb().Package) protoGoPackage := fmt.Sprintf(`"%s"`, ctx.GetProtoGo().Package) if isCallPkgSameToGrpcPkg { pbPackage = "" protoGoPackage = "" } aliasKeys := alias.Keys() sort.Strings(aliasKeys) if err = util.With("shared").GoFmt(true).Parse(text).SaveTo(map[string]any{ "name": callFilename, "alias": strings.Join(aliasKeys, pathx.NL), "head": head, "filePackage": childDir, "pbPackage": pbPackage, "protoGoPackage": protoGoPackage, "serviceName": serviceName, "functions": strings.Join(functions, pathx.NL), "interface": strings.Join(iFunctions, pathx.NL), }, filename, true); err != nil { return err } } return nil } func (g *Generator) genCallInCompatibility(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { dir := ctx.GetCall() service := proto.Service[0] head := util.GetHead(proto.Name) isCallPkgSameToPbPkg := ctx.GetCall().Filename == ctx.GetPb().Filename isCallPkgSameToGrpcPkg := ctx.GetCall().Filename == ctx.GetProtoGo().Filename callFilename, err := format.FileNamingFormat(cfg.NamingFormat, service.Name) if err != nil { return err } serviceName := stringx.From(service.Name).ToCamel() alias := collection.NewSet[string]() var hasSameNameBetweenMessageAndService bool for _, item := range proto.Message { msgName := getMessageName(*item.Message) if serviceName == msgName { hasSameNameBetweenMessageAndService = true } if !isCallPkgSameToPbPkg { alias.Add(fmt.Sprintf("%s = %s", parser.CamelCase(msgName), fmt.Sprintf("%s.%s", proto.PbPackage, parser.CamelCase(msgName)))) } } if hasSameNameBetweenMessageAndService { serviceName = stringx.From(service.Name + "_zrpc_client").ToCamel() } filename := filepath.Join(dir.Filename, fmt.Sprintf("%s.go", callFilename)) functions, err := g.genFunction(proto.PbPackage, serviceName, service, isCallPkgSameToGrpcPkg) if err != nil { return err } iFunctions, err := g.getInterfaceFuncs(proto.PbPackage, service, isCallPkgSameToGrpcPkg) if err != nil { return err } text, err := pathx.LoadTemplate(category, callTemplateFile, callTemplateText) if err != nil { return err } pbPackage := fmt.Sprintf(`"%s"`, ctx.GetPb().Package) protoGoPackage := fmt.Sprintf(`"%s"`, ctx.GetProtoGo().Package) if isCallPkgSameToGrpcPkg { pbPackage = "" protoGoPackage = "" } aliasKeys := alias.Keys() sort.Strings(aliasKeys) return util.With("shared").GoFmt(true).Parse(text).SaveTo(map[string]any{ "name": callFilename, "alias": strings.Join(aliasKeys, pathx.NL), "head": head, "filePackage": dir.Base, "pbPackage": pbPackage, "protoGoPackage": protoGoPackage, "serviceName": serviceName, "functions": strings.Join(functions, pathx.NL), "interface": strings.Join(iFunctions, pathx.NL), }, filename, true) } func getMessageName(msg proto.Message) string { list := []string{msg.Name} for { parent := msg.Parent if parent == nil { break } parentMsg, ok := parent.(*proto.Message) if !ok { break } tmp := []string{parentMsg.Name} list = append(tmp, list...) msg = *parentMsg } return strings.Join(list, "_") } func (g *Generator) genFunction(goPackage string, serviceName string, service parser.Service, isCallPkgSameToGrpcPkg bool) ([]string, error) { functions := make([]string, 0) for _, rpc := range service.RPC { text, err := pathx.LoadTemplate(category, callFunctionTemplateFile, callFunctionTemplate) if err != nil { return nil, err } comment := parser.GetComment(rpc.Doc()) streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") if isCallPkgSameToGrpcPkg { streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") } buffer, err := util.With("sharedFn").Parse(text).Execute(map[string]any{ "serviceName": serviceName, "rpcServiceName": parser.CamelCase(service.Name), "method": parser.CamelCase(rpc.Name), "package": goPackage, "pbRequest": parser.CamelCase(rpc.RequestType), "pbResponse": parser.CamelCase(rpc.ReturnsType), "hasComment": len(comment) > 0, "comment": comment, "hasReq": !rpc.StreamsRequest, "notStream": !rpc.StreamsRequest && !rpc.StreamsReturns, "streamBody": streamServer, "isCallPkgSameToGrpcPkg": isCallPkgSameToGrpcPkg, }) if err != nil { return nil, err } functions = append(functions, buffer.String()) } return functions, nil } func (g *Generator) getInterfaceFuncs(goPackage string, service parser.Service, isCallPkgSameToGrpcPkg bool) ([]string, error) { functions := make([]string, 0) for _, rpc := range service.RPC { text, err := pathx.LoadTemplate(category, callInterfaceFunctionTemplateFile, callInterfaceFunctionTemplate) if err != nil { return nil, err } comment := parser.GetComment(rpc.Doc()) streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") if isCallPkgSameToGrpcPkg { streamServer = fmt.Sprintf("%s_%s%s", parser.CamelCase(service.Name), parser.CamelCase(rpc.Name), "Client") } buffer, err := util.With("interfaceFn").Parse(text).Execute( map[string]any{ "hasComment": len(comment) > 0, "comment": comment, "method": parser.CamelCase(rpc.Name), "hasReq": !rpc.StreamsRequest, "pbRequest": parser.CamelCase(rpc.RequestType), "notStream": !rpc.StreamsRequest && !rpc.StreamsReturns, "pbResponse": parser.CamelCase(rpc.ReturnsType), "streamBody": streamServer, }) if err != nil { return nil, err } functions = append(functions, buffer.String()) } return functions, nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/generator.go
tools/goctl/rpc/generator/generator.go
package generator import ( "log" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/env" "github.com/zeromicro/go-zero/tools/goctl/util/console" ) // Generator defines the environment needs of rpc service generation type Generator struct { log console.Console cfg *conf.Config verbose bool } // NewGenerator returns an instance of Generator func NewGenerator(style string, verbose bool) *Generator { cfg, err := conf.NewConfig(style) if err != nil { log.Fatalln(err) } colorLogger := console.NewColorConsole(verbose) return &Generator{ log: colorLogger, cfg: cfg, verbose: verbose, } } // Prepare provides environment detection generated by rpc service, // including go environment, protoc, whether protoc-gen-go is installed or not func (g *Generator) Prepare() error { return env.Prepare(true, true, g.verbose) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/mkdir.go
tools/goctl/rpc/generator/mkdir.go
package generator import ( "path/filepath" "strings" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util/ctx" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) const ( wd = "wd" etc = "etc" internal = "internal" config = "config" logic = "logic" server = "server" svc = "svc" pb = "pb" protoGo = "proto-go" call = "call" ) type ( // DirContext defines a rpc service directories context DirContext interface { GetCall() Dir GetEtc() Dir GetInternal() Dir GetConfig() Dir GetLogic() Dir GetServer() Dir GetSvc() Dir GetPb() Dir GetProtoGo() Dir GetMain() Dir GetServiceName() stringx.String SetPbDir(pbDir, grpcDir string) } // Dir defines a directory Dir struct { Base string Filename string Package string GetChildPackage func(childPath string) (string, error) } defaultDirContext struct { inner map[string]Dir serviceName stringx.String ctx *ctx.ProjectContext } ) func mkdir(ctx *ctx.ProjectContext, proto parser.Proto, conf *conf.Config, c *ZRpcContext) (DirContext, error) { inner := make(map[string]Dir) etcDir := filepath.Join(ctx.WorkDir, "etc") clientDir := filepath.Join(ctx.WorkDir, "client") internalDir := filepath.Join(ctx.WorkDir, "internal") configDir := filepath.Join(internalDir, "config") logicDir := filepath.Join(internalDir, "logic") serverDir := filepath.Join(internalDir, "server") svcDir := filepath.Join(internalDir, "svc") pbDir := filepath.Join(ctx.WorkDir, proto.GoPackage) protoGoDir := pbDir if c != nil { pbDir = c.ProtoGenGrpcDir protoGoDir = c.ProtoGenGoDir } getChildPackage := func(parent, childPath string) (string, error) { child := strings.TrimPrefix(childPath, parent) abs := filepath.Join(parent, strings.ToLower(child)) if c.Multiple { if err := pathx.MkdirIfNotExist(abs); err != nil { return "", err } } childPath = strings.TrimPrefix(abs, ctx.Dir) pkg := filepath.Join(ctx.Path, childPath) return filepath.ToSlash(pkg), nil } var callClientDir string if !c.Multiple { callDir := filepath.Join(ctx.WorkDir, strings.ToLower(stringx.From(proto.Service[0].Name).ToCamel())) if strings.EqualFold(proto.Service[0].Name, filepath.Base(proto.GoPackage)) { var err error clientDir, err = format.FileNamingFormat(conf.NamingFormat, proto.Service[0].Name+"_client") if err != nil { return nil, err } callDir = filepath.Join(ctx.WorkDir, clientDir) } callClientDir = callDir } else { callClientDir = clientDir } if c.IsGenClient { inner[call] = Dir{ Filename: callClientDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(callClientDir, ctx.Dir))), Base: filepath.Base(callClientDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(callClientDir, childPath) }, } } inner[wd] = Dir{ Filename: ctx.WorkDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(ctx.WorkDir, ctx.Dir))), Base: filepath.Base(ctx.WorkDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(ctx.WorkDir, childPath) }, } inner[etc] = Dir{ Filename: etcDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(etcDir, ctx.Dir))), Base: filepath.Base(etcDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(etcDir, childPath) }, } inner[internal] = Dir{ Filename: internalDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(internalDir, ctx.Dir))), Base: filepath.Base(internalDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(internalDir, childPath) }, } inner[config] = Dir{ Filename: configDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(configDir, ctx.Dir))), Base: filepath.Base(configDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(configDir, childPath) }, } inner[logic] = Dir{ Filename: logicDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(logicDir, ctx.Dir))), Base: filepath.Base(logicDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(logicDir, childPath) }, } inner[server] = Dir{ Filename: serverDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(serverDir, ctx.Dir))), Base: filepath.Base(serverDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(serverDir, childPath) }, } inner[svc] = Dir{ Filename: svcDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(svcDir, ctx.Dir))), Base: filepath.Base(svcDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(svcDir, childPath) }, } inner[pb] = Dir{ Filename: pbDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(pbDir, ctx.Dir))), Base: filepath.Base(pbDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(pbDir, childPath) }, } inner[protoGo] = Dir{ Filename: protoGoDir, Package: filepath.ToSlash(filepath.Join(ctx.Path, strings.TrimPrefix(protoGoDir, ctx.Dir))), Base: filepath.Base(protoGoDir), GetChildPackage: func(childPath string) (string, error) { return getChildPackage(protoGoDir, childPath) }, } for _, v := range inner { err := pathx.MkdirIfNotExist(v.Filename) if err != nil { return nil, err } } serviceName := strings.TrimSuffix(proto.Name, filepath.Ext(proto.Name)) return &defaultDirContext{ ctx: ctx, inner: inner, serviceName: stringx.From(strings.ReplaceAll(serviceName, "-", "")), }, nil } func (d *defaultDirContext) SetPbDir(pbDir, grpcDir string) { d.inner[pb] = Dir{ Filename: pbDir, Package: filepath.ToSlash(filepath.Join(d.ctx.Path, strings.TrimPrefix(pbDir, d.ctx.Dir))), Base: filepath.Base(pbDir), } d.inner[protoGo] = Dir{ Filename: grpcDir, Package: filepath.ToSlash(filepath.Join(d.ctx.Path, strings.TrimPrefix(grpcDir, d.ctx.Dir))), Base: filepath.Base(grpcDir), } } func (d *defaultDirContext) GetCall() Dir { return d.inner[call] } func (d *defaultDirContext) GetEtc() Dir { return d.inner[etc] } func (d *defaultDirContext) GetInternal() Dir { return d.inner[internal] } func (d *defaultDirContext) GetConfig() Dir { return d.inner[config] } func (d *defaultDirContext) GetLogic() Dir { return d.inner[logic] } func (d *defaultDirContext) GetServer() Dir { return d.inner[server] } func (d *defaultDirContext) GetSvc() Dir { return d.inner[svc] } func (d *defaultDirContext) GetPb() Dir { return d.inner[pb] } func (d *defaultDirContext) GetProtoGo() Dir { return d.inner[protoGo] } func (d *defaultDirContext) GetMain() Dir { return d.inner[wd] } func (d *defaultDirContext) GetServiceName() stringx.String { return d.serviceName } // Valid returns true if the directory is valid func (d *Dir) Valid() bool { return len(d.Filename) > 0 && len(d.Package) > 0 }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/template_test.go
tools/goctl/rpc/generator/template_test.go
package generator import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) func TestGenTemplates(t *testing.T) { _ = Clean() err := GenTemplates() assert.Nil(t, err) } func TestRevertTemplate(t *testing.T) { _ = Clean() err := GenTemplates() assert.Nil(t, err) fp, err := pathx.GetTemplateDir(category) if err != nil { return } mainTpl := filepath.Join(fp, mainTemplateFile) data, err := os.ReadFile(mainTpl) if err != nil { return } assert.Equal(t, templates[mainTemplateFile], string(data)) err = RevertTemplate("test") if err != nil { assert.Equal(t, "test: no such file name", err.Error()) } err = os.WriteFile(mainTpl, []byte("modify"), os.ModePerm) if err != nil { return } data, err = os.ReadFile(mainTpl) if err != nil { return } assert.Equal(t, "modify", string(data)) err = RevertTemplate(mainTemplateFile) assert.Nil(t, err) data, err = os.ReadFile(mainTpl) if err != nil { return } assert.Equal(t, templates[mainTemplateFile], string(data)) } func TestClean(t *testing.T) { _ = Clean() err := GenTemplates() assert.Nil(t, err) fp, err := pathx.GetTemplateDir(category) if err != nil { return } mainTpl := filepath.Join(fp, mainTemplateFile) _, err = os.Stat(mainTpl) assert.Nil(t, err) err = Clean() assert.Nil(t, err) _, err = os.Stat(mainTpl) assert.NotNil(t, err) } func TestUpdate(t *testing.T) { _ = Clean() err := GenTemplates() assert.Nil(t, err) fp, err := pathx.GetTemplateDir(category) if err != nil { return } mainTpl := filepath.Join(fp, mainTemplateFile) err = os.WriteFile(mainTpl, []byte("modify"), os.ModePerm) if err != nil { return } data, err := os.ReadFile(mainTpl) if err != nil { return } assert.Equal(t, "modify", string(data)) assert.Nil(t, Update()) data, err = os.ReadFile(mainTpl) if err != nil { return } assert.Equal(t, templates[mainTemplateFile], string(data)) } func TestGetCategory(t *testing.T) { _ = Clean() result := Category() assert.Equal(t, category, result) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genmain.go
tools/goctl/rpc/generator/genmain.go
package generator import ( _ "embed" "fmt" "path/filepath" "strings" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) //go:embed main.tpl var mainTemplate string type MainServiceTemplateData struct { GRPCService string Service string ServerPkg string Pkg string } // GenMain generates the main file of the rpc service, which is an rpc service program call entry func (g *Generator) GenMain(ctx DirContext, proto parser.Proto, cfg *conf.Config, c *ZRpcContext) error { mainFilename, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source()) if err != nil { return err } fileName := filepath.Join(ctx.GetMain().Filename, fmt.Sprintf("%v.go", mainFilename)) imports := make([]string, 0) pbImport := fmt.Sprintf(`"%v"`, ctx.GetPb().Package) svcImport := fmt.Sprintf(`"%v"`, ctx.GetSvc().Package) configImport := fmt.Sprintf(`"%v"`, ctx.GetConfig().Package) imports = append(imports, configImport, pbImport, svcImport) var serviceNames []MainServiceTemplateData for _, e := range proto.Service { var ( remoteImport string serverPkg string ) if !c.Multiple { serverPkg = "server" remoteImport = fmt.Sprintf(`"%v"`, ctx.GetServer().Package) } else { childPkg, err := ctx.GetServer().GetChildPackage(e.Name) if err != nil { return err } serverPkg = filepath.Base(childPkg + "Server") remoteImport = fmt.Sprintf(`%s "%v"`, serverPkg, childPkg) } imports = append(imports, remoteImport) serviceNames = append(serviceNames, MainServiceTemplateData{ GRPCService: parser.CamelCase(e.Name), Service: stringx.From(e.Name).ToCamel(), ServerPkg: serverPkg, Pkg: proto.PbPackage, }) } text, err := pathx.LoadTemplate(category, mainTemplateFile, mainTemplate) if err != nil { return err } etcFileName, err := format.FileNamingFormat(cfg.NamingFormat, ctx.GetServiceName().Source()) if err != nil { return err } return util.With("main").GoFmt(true).Parse(text).SaveTo(map[string]any{ "serviceName": etcFileName, "imports": strings.Join(imports, pathx.NL), "pkg": proto.PbPackage, "serviceNames": serviceNames, }, fileName, false) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/genlogic.go
tools/goctl/rpc/generator/genlogic.go
package generator import ( _ "embed" "fmt" "path/filepath" "strings" "github.com/zeromicro/go-zero/core/collection" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) const logicFunctionTemplate = `{{if .hasComment}}{{.comment}}{{end}} func (l *{{.logicName}}) {{.method}} ({{if .hasReq}}in {{.request}}{{if .stream}},stream {{.streamBody}}{{end}}{{else}}stream {{.streamBody}}{{end}}) ({{if .hasReply}}{{.response}},{{end}} error) { // todo: add your logic here and delete this line return {{if .hasReply}}&{{.responseType}}{},{{end}} nil } ` //go:embed logic.tpl var logicTemplate string // GenLogic generates the logic file of the rpc service, which corresponds to the RPC definition items in proto. func (g *Generator) GenLogic(ctx DirContext, proto parser.Proto, cfg *conf.Config, c *ZRpcContext) error { if !c.Multiple { return g.genLogicInCompatibility(ctx, proto, cfg) } return g.genLogicGroup(ctx, proto, cfg) } func (g *Generator) genLogicInCompatibility(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { dir := ctx.GetLogic() service := proto.Service[0].Service.Name for _, rpc := range proto.Service[0].RPC { logicName := fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) logicFilename, err := format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") if err != nil { return err } filename := filepath.Join(dir.Filename, logicFilename+".go") functions, err := g.genLogicFunction(service, proto.PbPackage, logicName, rpc) if err != nil { return err } imports := collection.NewSet[string]() imports.Add(fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)) imports.Add(fmt.Sprintf(`"%v"`, ctx.GetPb().Package)) text, err := pathx.LoadTemplate(category, logicTemplateFileFile, logicTemplate) if err != nil { return err } err = util.With("logic").GoFmt(true).Parse(text).SaveTo(map[string]any{ "logicName": fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()), "functions": functions, "packageName": "logic", "imports": strings.Join(imports.Keys(), pathx.NL), }, filename, false) if err != nil { return err } } return nil } func (g *Generator) genLogicGroup(ctx DirContext, proto parser.Proto, cfg *conf.Config) error { dir := ctx.GetLogic() for _, item := range proto.Service { serviceName := item.Name for _, rpc := range item.RPC { var ( err error filename string logicName string logicFilename string packageName string ) logicName = fmt.Sprintf("%sLogic", stringx.From(rpc.Name).ToCamel()) childPkg, err := dir.GetChildPackage(serviceName) if err != nil { return err } serviceDir := filepath.Base(childPkg) nameJoin := fmt.Sprintf("%s_logic", serviceName) packageName = strings.ToLower(stringx.From(nameJoin).ToCamel()) logicFilename, err = format.FileNamingFormat(cfg.NamingFormat, rpc.Name+"_logic") if err != nil { return err } filename = filepath.Join(dir.Filename, serviceDir, logicFilename+".go") functions, err := g.genLogicFunction(serviceName, proto.PbPackage, logicName, rpc) if err != nil { return err } imports := collection.NewSet[string]() imports.Add(fmt.Sprintf(`"%v"`, ctx.GetSvc().Package)) imports.Add(fmt.Sprintf(`"%v"`, ctx.GetPb().Package)) text, err := pathx.LoadTemplate(category, logicTemplateFileFile, logicTemplate) if err != nil { return err } if err = util.With("logic").GoFmt(true).Parse(text).SaveTo(map[string]any{ "logicName": logicName, "functions": functions, "packageName": packageName, "imports": strings.Join(imports.Keys(), pathx.NL), }, filename, false); err != nil { return err } } } return nil } func (g *Generator) genLogicFunction(serviceName, goPackage, logicName string, rpc *parser.RPC) (string, error) { functions := make([]string, 0) text, err := pathx.LoadTemplate(category, logicFuncTemplateFileFile, logicFunctionTemplate) if err != nil { return "", err } comment := parser.GetComment(rpc.Doc()) streamServer := fmt.Sprintf("%s.%s_%s%s", goPackage, parser.CamelCase(serviceName), parser.CamelCase(rpc.Name), "Server") buffer, err := util.With("fun").Parse(text).Execute(map[string]any{ "logicName": logicName, "method": parser.CamelCase(rpc.Name), "hasReq": !rpc.StreamsRequest, "request": fmt.Sprintf("*%s.%s", goPackage, parser.CamelCase(rpc.RequestType)), "hasReply": !rpc.StreamsRequest && !rpc.StreamsReturns, "response": fmt.Sprintf("*%s.%s", goPackage, parser.CamelCase(rpc.ReturnsType)), "responseType": fmt.Sprintf("%s.%s", goPackage, parser.CamelCase(rpc.ReturnsType)), "stream": rpc.StreamsRequest || rpc.StreamsReturns, "streamBody": streamServer, "hasComment": len(comment) > 0, "comment": comment, }) if err != nil { return "", err } functions = append(functions, buffer.String()) return strings.Join(functions, pathx.NL), nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/template.go
tools/goctl/rpc/generator/template.go
package generator import ( "fmt" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const ( category = "rpc" callTemplateFile = "call.tpl" callInterfaceFunctionTemplateFile = "call-interface-func.tpl" callFunctionTemplateFile = "call-func.tpl" configTemplateFileFile = "config.tpl" etcTemplateFileFile = "etc.tpl" logicTemplateFileFile = "logic.tpl" logicFuncTemplateFileFile = "logic-func.tpl" mainTemplateFile = "main.tpl" serverTemplateFile = "server.tpl" serverFuncTemplateFile = "server-func.tpl" svcTemplateFile = "svc.tpl" rpcTemplateFile = "template.tpl" ) var templates = map[string]string{ callTemplateFile: callTemplateText, configTemplateFileFile: configTemplate, etcTemplateFileFile: etcTemplate, logicTemplateFileFile: logicTemplate, logicFuncTemplateFileFile: logicFunctionTemplate, mainTemplateFile: mainTemplate, serverTemplateFile: serverTemplate, serverFuncTemplateFile: functionTemplate, svcTemplateFile: svcTemplate, rpcTemplateFile: rpcTemplateText, } // GenTemplates is the entry for command goctl template, // it will create the specified category func GenTemplates() error { return pathx.InitTemplates(category, templates) } // RevertTemplate restores the deleted template files func RevertTemplate(name string) error { content, ok := templates[name] if !ok { return fmt.Errorf("%s: no such file name", name) } return pathx.CreateTemplate(category, name, content) } // Clean deletes all template files func Clean() error { return pathx.Clean(category) } // Update is used to update the template files, it will delete the existing old templates at first, // and then create the latest template files func Update() error { err := Clean() if err != nil { return err } return pathx.InitTemplates(category, templates) } // Category returns a const string value for rpc template category func Category() string { return category }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/generator/gensvc.go
tools/goctl/rpc/generator/gensvc.go
package generator import ( _ "embed" "fmt" "path/filepath" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/rpc/parser" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) //go:embed svc.tpl var svcTemplate string // GenSvc generates the servicecontext.go file, which is the resource dependency of a service, // such as rpc dependency, model dependency, etc. func (g *Generator) GenSvc(ctx DirContext, _ parser.Proto, cfg *conf.Config) error { dir := ctx.GetSvc() svcFilename, err := format.FileNamingFormat(cfg.NamingFormat, "service_context") if err != nil { return err } fileName := filepath.Join(dir.Filename, svcFilename+".go") text, err := pathx.LoadTemplate(category, svcTemplateFile, svcTemplate) if err != nil { return err } return util.With("svc").GoFmt(true).Parse(text).SaveTo(map[string]any{ "imports": fmt.Sprintf(`"%v"`, ctx.GetConfig().Package), }, fileName, false) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/cli/cli.go
tools/goctl/rpc/cli/cli.go
package cli import ( "errors" "fmt" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/rpc/generator" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/console" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) var ( // VarStringOutput describes the output. VarStringOutput string // VarStringHome describes the goctl home. VarStringHome string // VarStringRemote describes the remote git repository. VarStringRemote string // VarStringBranch describes the git branch. VarStringBranch string // VarStringSliceGoOut describes the go output. VarStringSliceGoOut []string // VarStringSliceGoGRPCOut describes the grpc output. VarStringSliceGoGRPCOut []string // VarStringSlicePlugin describes the protoc plugin. VarStringSlicePlugin []string // VarStringSliceProtoPath describes the proto path. VarStringSliceProtoPath []string // VarStringSliceGoOpt describes the go options. VarStringSliceGoOpt []string // VarStringSliceGoGRPCOpt describes the grpc options. VarStringSliceGoGRPCOpt []string // VarStringStyle describes the style of output files. VarStringStyle string // VarStringZRPCOut describes the zRPC output. VarStringZRPCOut string // VarBoolIdea describes whether idea or not VarBoolIdea bool // VarBoolVerbose describes whether verbose. VarBoolVerbose bool // VarBoolMultiple describes whether support generating multiple rpc services or not. VarBoolMultiple bool // VarBoolClient describes whether to generate rpc client VarBoolClient bool // VarStringModule describes the module name for go.mod. VarStringModule string ) // RPCNew is to generate rpc greet service, this greet service can speed // up your understanding of the zrpc service structure func RPCNew(_ *cobra.Command, args []string) error { rpcname := args[0] ext := filepath.Ext(rpcname) if len(ext) > 0 { return fmt.Errorf("unexpected ext: %s", ext) } style := VarStringStyle home := VarStringHome remote := VarStringRemote branch := VarStringBranch verbose := VarBoolVerbose if len(remote) > 0 { repo, _ := util.CloneIntoGitHome(remote, branch) if len(repo) > 0 { home = repo } } if len(home) > 0 { pathx.RegisterGoctlHome(home) } protoName := rpcname + ".proto" filename := filepath.Join(".", rpcname, protoName) src, err := filepath.Abs(filename) if err != nil { return err } err = generator.ProtoTmpl(src) if err != nil { return err } var ctx generator.ZRpcContext ctx.Src = src ctx.GoOutput = filepath.Dir(src) ctx.GrpcOutput = filepath.Dir(src) ctx.IsGooglePlugin = true ctx.Output = filepath.Dir(src) ctx.ProtocCmd = fmt.Sprintf("protoc -I=%s %s --go_out=%s --go-grpc_out=%s", filepath.Dir(src), filepath.Base(src), filepath.Dir(src), filepath.Dir(src)) ctx.IsGenClient = VarBoolClient ctx.Module = VarStringModule grpcOptList := VarStringSliceGoGRPCOpt if len(grpcOptList) > 0 { ctx.ProtocCmd += " --go-grpc_opt=" + strings.Join(grpcOptList, ",") } goOptList := VarStringSliceGoOpt if len(goOptList) > 0 { ctx.ProtocCmd += " --go_opt=" + strings.Join(goOptList, ",") } g := generator.NewGenerator(style, verbose) return g.Generate(&ctx) } // RPCTemplate is the entry for generate rpc template func RPCTemplate(latest bool) error { if !latest { console.Warning("deprecated: goctl rpc template -o is deprecated and will be removed in the future, use goctl rpc -o instead") } protoFile := VarStringOutput home := VarStringHome remote := VarStringRemote branch := VarStringBranch if len(remote) > 0 { repo, _ := util.CloneIntoGitHome(remote, branch) if len(repo) > 0 { home = repo } } if len(home) > 0 { pathx.RegisterGoctlHome(home) } if len(protoFile) == 0 { return errors.New("missing -o") } return generator.ProtoTmpl(protoFile) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/cli/zrpc.go
tools/goctl/rpc/cli/zrpc.go
package cli import ( "errors" "os" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/rpc/generator" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) var ( errInvalidGrpcOutput = errors.New("ZRPC: missing --go-grpc_out") errInvalidGoOutput = errors.New("ZRPC: missing --go_out") errInvalidZrpcOutput = errors.New("ZRPC: missing zrpc output, please use --zrpc_out to specify the output") ) // ZRPC generates grpc code directly by protoc and generates // zrpc code by goctl. func ZRPC(_ *cobra.Command, args []string) error { protocArgs := wrapProtocCmd("protoc", args) pwd, err := os.Getwd() if err != nil { return err } source := args[0] grpcOutList := VarStringSliceGoGRPCOut goOutList := VarStringSliceGoOut zrpcOut := VarStringZRPCOut style := VarStringStyle home := VarStringHome remote := VarStringRemote branch := VarStringBranch verbose := VarBoolVerbose if len(grpcOutList) == 0 { return errInvalidGrpcOutput } if len(goOutList) == 0 { return errInvalidGoOutput } goOut := goOutList[len(goOutList)-1] grpcOut := grpcOutList[len(grpcOutList)-1] if len(goOut) == 0 { return errInvalidGrpcOutput } if len(zrpcOut) == 0 { return errInvalidZrpcOutput } goOutAbs, err := filepath.Abs(goOut) if err != nil { return err } grpcOutAbs, err := filepath.Abs(grpcOut) if err != nil { return err } err = pathx.MkdirIfNotExist(goOutAbs) if err != nil { return err } err = pathx.MkdirIfNotExist(grpcOutAbs) if err != nil { return err } if len(remote) > 0 { repo, _ := util.CloneIntoGitHome(remote, branch) if len(repo) > 0 { home = repo } } if len(home) > 0 { pathx.RegisterGoctlHome(home) } if !filepath.IsAbs(zrpcOut) { zrpcOut = filepath.Join(pwd, zrpcOut) } isGooglePlugin := len(grpcOut) > 0 goOut, err = filepath.Abs(goOut) if err != nil { return err } grpcOut, err = filepath.Abs(grpcOut) if err != nil { return err } zrpcOut, err = filepath.Abs(zrpcOut) if err != nil { return err } var ctx generator.ZRpcContext ctx.Multiple = VarBoolMultiple ctx.Src = source ctx.GoOutput = goOut ctx.GrpcOutput = grpcOut ctx.IsGooglePlugin = isGooglePlugin ctx.Output = zrpcOut ctx.ProtocCmd = strings.Join(protocArgs, " ") ctx.IsGenClient = VarBoolClient ctx.Module = VarStringModule g := generator.NewGenerator(style, verbose) return g.Generate(&ctx) } func wrapProtocCmd(name string, args []string) []string { ret := append([]string{name}, args...) for _, protoPath := range VarStringSliceProtoPath { ret = append(ret, "--proto_path", protoPath) } for _, goOpt := range VarStringSliceGoOpt { ret = append(ret, "--go_opt", goOpt) } for _, goGRPCOpt := range VarStringSliceGoGRPCOpt { ret = append(ret, "--go-grpc_opt", goGRPCOpt) } for _, goOut := range VarStringSliceGoOut { ret = append(ret, "--go_out", goOut) } for _, goGRPCOut := range VarStringSliceGoGRPCOut { ret = append(ret, "--go-grpc_out", goGRPCOut) } for _, plugin := range VarStringSlicePlugin { ret = append(ret, "--plugin="+plugin) } return ret }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/parser.go
tools/goctl/rpc/parser/parser.go
package parser import ( "errors" "go/token" "os" "path/filepath" "strings" "unicode" "unicode/utf8" "github.com/emicklei/proto" ) type ( // DefaultProtoParser types an empty struct DefaultProtoParser struct{} ) var ErrGoPackage = errors.New(`option go_package = "" field is not filled in`) // NewDefaultProtoParser creates a new instance func NewDefaultProtoParser() *DefaultProtoParser { return &DefaultProtoParser{} } // Parse provides to parse the proto file into a golang structure, // which is convenient for subsequent rpc generation and use func (p *DefaultProtoParser) Parse(src string, multiple ...bool) (Proto, error) { var ret Proto abs, err := filepath.Abs(src) if err != nil { return Proto{}, err } r, err := os.Open(abs) if err != nil { return ret, err } defer r.Close() parser := proto.NewParser(r) set, err := parser.Parse() if err != nil { return ret, err } var serviceList Services proto.Walk( set, proto.WithImport(func(i *proto.Import) { ret.Import = append(ret.Import, Import{Import: i}) }), proto.WithMessage(func(message *proto.Message) { ret.Message = append(ret.Message, Message{Message: message}) }), proto.WithPackage(func(p *proto.Package) { ret.Package = Package{Package: p} }), proto.WithService(func(service *proto.Service) { serv := Service{Service: service} elements := service.Elements for _, el := range elements { v, _ := el.(*proto.RPC) if v == nil { continue } serv.RPC = append(serv.RPC, &RPC{RPC: v}) } serviceList = append(serviceList, serv) }), proto.WithOption(func(option *proto.Option) { if option.Name == "go_package" { ret.GoPackage = option.Constant.Source } }), ) if err = serviceList.validate(abs, multiple...); err != nil { return ret, err } if len(ret.GoPackage) == 0 { if ret.Package.Package == nil { return ret, ErrGoPackage } ret.GoPackage = ret.Package.Name } ret.PbPackage = GoSanitized(filepath.Base(ret.GoPackage)) ret.Src = abs ret.Name = filepath.Base(abs) ret.Service = serviceList return ret, nil } // GoSanitized copy from protobuf, for more information, please see google.golang.org/protobuf@v1.25.0/internal/strs/strings.go:71 func GoSanitized(s string) string { // Sanitize the input to the set of valid characters, // which must be '_' or be in the Unicode L or N categories. s = strings.Map(func(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) { return r } return '_' }, s) // Prepend '_' in the event of a Go keyword conflict or if // the identifier is invalid (does not start in the Unicode L category). r, _ := utf8.DecodeRuneInString(s) if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) { return "_" + s } return s } // CamelCase copy from protobuf, for more information, please see github.com/golang/protobuf@v1.4.2/protoc-gen-go/generator/generator.go:2648 func CamelCase(s string) string { if s == "" { return "" } t := make([]byte, 0, 32) i := 0 if s[0] == '_' { // Need a capital letter; drop the '_'. t = append(t, 'X') i++ } // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. for ; i < len(s); i++ { c := s[i] if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) { continue // Skip the underscore in s. } if isASCIIDigit(c) { t = append(t, c) continue } // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c ^= ' ' // Make it a capital letter. } t = append(t, c) // Guaranteed not lower case. // Accept lower case sequence that follows. for i+1 < len(s) && isASCIILower(s[i+1]) { i++ t = append(t, s[i]) } } return string(t) } func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } // Is c an ASCII digit? func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/comment.go
tools/goctl/rpc/parser/comment.go
package parser import ( "strings" "github.com/emicklei/proto" ) // GetComment returns content with prefix // func GetComment(comment *proto.Comment) string { if comment == nil { return "" } return "// " + strings.TrimSpace(comment.Message()) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/rpc.go
tools/goctl/rpc/parser/rpc.go
package parser import "github.com/emicklei/proto" // RPC embeds proto.RPC type RPC struct { *proto.RPC }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/option.go
tools/goctl/rpc/parser/option.go
package parser import "github.com/emicklei/proto" // Option embeds proto.Option type Option struct { *proto.Option }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/service.go
tools/goctl/rpc/parser/service.go
package parser import ( "errors" "fmt" "path/filepath" "strings" "github.com/emicklei/proto" ) type ( // Services is a slice of Service. Services []Service // Service describes the rpc service, which is the relevant // content after the translation of the proto file Service struct { *proto.Service RPC []*RPC } ) func (s Services) validate(filename string, multipleOpt ...bool) error { if len(s) == 0 { return errors.New("rpc service not found") } var multiple bool for _, c := range multipleOpt { multiple = c } if !multiple && len(s) > 1 { return errors.New("only one service expected") } name := filepath.Base(filename) for _, service := range s { for _, rpc := range service.RPC { if strings.Contains(rpc.RequestType, ".") { return fmt.Errorf("line %v:%v, request type must defined in %s", rpc.Position.Line, rpc.Position.Column, name) } if strings.Contains(rpc.ReturnsType, ".") { return fmt.Errorf("line %v:%v, returns type must defined in %s", rpc.Position.Line, rpc.Position.Column, name) } } } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/proto.go
tools/goctl/rpc/parser/proto.go
package parser // Proto describes a proto file, type Proto struct { Src string Name string Package Package PbPackage string GoPackage string Import []Import Message []Message Service Services }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/parser_test.go
tools/goctl/rpc/parser/parser_test.go
package parser import ( "sort" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestDefaultProtoParse(t *testing.T) { p := NewDefaultProtoParser() data, err := p.Parse("./test.proto") assert.Nil(t, err) assert.Equal(t, "base.proto", func() string { ip := data.Import[0] return ip.Filename }()) assert.Equal(t, "test", data.Package.Name) assert.Equal(t, true, data.GoPackage == "go") assert.Equal(t, true, data.PbPackage == "_go") assert.Equal(t, []string{"Inline", "Inner", "TestMessage", "TestReply", "TestReq"}, func() []string { var list []string for _, item := range data.Message { list = append(list, item.Name) } sort.Strings(list) return list }()) assert.Equal(t, true, func() bool { if len(data.Service) != 1 { return false } s := data.Service[0] if s.Name != "TestService" { return false } rpcOne := s.RPC[0] return rpcOne.Name == "TestRpcOne" && rpcOne.RequestType == "TestReq" && rpcOne.ReturnsType == "TestReply" }()) } func TestDefaultProtoParseCaseInvalidRequestType(t *testing.T) { p := NewDefaultProtoParser() _, err := p.Parse("./test_invalid_request.proto") assert.True(t, true, func() bool { return strings.Contains(err.Error(), "request type must defined in") }()) } func TestDefaultProtoParseCaseInvalidResponseType(t *testing.T) { p := NewDefaultProtoParser() _, err := p.Parse("./test_invalid_response.proto") assert.True(t, true, func() bool { return strings.Contains(err.Error(), "response type must defined in") }()) } func TestDefaultProtoParseError(t *testing.T) { p := NewDefaultProtoParser() _, err := p.Parse("./nil.proto") assert.NotNil(t, err) } func TestDefaultProtoParse_Option(t *testing.T) { p := NewDefaultProtoParser() data, err := p.Parse("./test_option.proto") assert.Nil(t, err) assert.Equal(t, "github.com/zeromicro/go-zero", data.GoPackage) assert.Equal(t, "go_zero", data.PbPackage) } func TestDefaultProtoParse_Option2(t *testing.T) { p := NewDefaultProtoParser() data, err := p.Parse("./test_option2.proto") assert.Nil(t, err) assert.Equal(t, "stream", data.GoPackage) assert.Equal(t, "stream", data.PbPackage) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/message.go
tools/goctl/rpc/parser/message.go
package parser import "github.com/emicklei/proto" // Message embeds proto.Message type Message struct { *proto.Message }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/package.go
tools/goctl/rpc/parser/package.go
package parser import "github.com/emicklei/proto" // Package defines the protobuf package. type Package struct { *proto.Package }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/rpc/parser/import.go
tools/goctl/rpc/parser/import.go
package parser import "github.com/emicklei/proto" // Import embeds proto.Import type Import struct { *proto.Import }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/bug/bug.go
tools/goctl/bug/bug.go
package bug import ( "fmt" "net/url" "os/exec" "runtime" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/internal/version" ) const ( windows = "windows" darwin = "darwin" windowsOpen = "start" darwinOpen = "open" linuxOpen = "xdg-open" os = "OS" arch = "ARCH" goctlVersion = "GOCTL_VERSION" goVersion = "GO_VERSION" ) var openCmd = map[string]string{ windows: windowsOpen, darwin: darwinOpen, } func runE(_ *cobra.Command, _ []string) error { env := getEnv() content := fmt.Sprintf(issueTemplate, version.BuildVersion, env.string()) content = url.QueryEscape(content) url := fmt.Sprintf("https://github.com/zeromicro/go-zero/issues/new?body=%s", content) goos := runtime.GOOS var cmd string var args []string cmd, ok := openCmd[goos] if !ok { cmd = linuxOpen } if goos == windows { args = []string{"/c", "start"} } args = append(args, url) return exec.Command(cmd, args...).Start() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/bug/issue.go
tools/goctl/bug/issue.go
package bug const issueTemplate = ` <!-- Please answer these questions before submitting your issue. Thanks! --> ### What category of issue (<code>goctl</code> or <code>sdk</code>)? ### What type of issue (<code>feature</code>|<code>bug</code>|<code>suggestion</code>)? ### What version of Goctl are you using (<code>goctl --version</code>)? <pre> $ goctl --version %s </pre> ### Does this issue reproduce with the latest release? ### What operating system and processor architecture are you using ? <pre> %s </pre> ### What did you do? <!-- If possible, provide a recipe for reproducing the error. A complete runnable program is good. A link on play.golang.org is best. --> ### What did you expect to see? ### What did you see instead? `
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/bug/cmd.go
tools/goctl/bug/cmd.go
package bug import ( "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax" ) // Cmd describes a bug command. var Cmd = cobrax.NewCommand("bug", cobrax.WithRunE(runE), cobrax.WithArgs(cobra.NoArgs))
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/bug/env.go
tools/goctl/bug/env.go
package bug import ( "bytes" "fmt" "runtime" "strings" "github.com/zeromicro/go-zero/tools/goctl/internal/version" ) type env map[string]string func (e env) string() string { if e == nil { return "" } w := bytes.NewBuffer(nil) for k, v := range e { w.WriteString(fmt.Sprintf("%s = %q\n", k, v)) } return strings.TrimSuffix(w.String(), "\n") } func getEnv() env { e := make(env) e[os] = runtime.GOOS e[arch] = runtime.GOARCH e[goctlVersion] = version.BuildVersion e[goVersion] = runtime.Version() return e }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/test/test.go
tools/goctl/test/test.go
package test import ( "encoding/json" "testing" "github.com/stretchr/testify/assert" ) type Data[T, Y any] struct { Name string Input T Want Y E error } type Option[T, Y any] func(*Executor[T, Y]) type assertFn[Y any] func(t *testing.T, expected, actual Y) bool func WithComparison[T, Y any](comparisonFn assertFn[Y]) Option[T, Y] { return func(e *Executor[T, Y]) { e.equalFn = comparisonFn } } type Executor[T, Y any] struct { list []Data[T, Y] equalFn assertFn[Y] } func NewExecutor[T, Y any](opt ...Option[T, Y]) *Executor[T, Y] { e := &Executor[T, Y]{} opt = append(opt, WithComparison[T, Y](func(t *testing.T, expected, actual Y) bool { gotBytes, err := json.Marshal(actual) if err != nil { t.Fatal(err) return false } wantBytes, err := json.Marshal(expected) if err != nil { t.Fatal(err) return false } return assert.JSONEq(t, string(wantBytes), string(gotBytes)) })) for _, o := range opt { o(e) } return e } func (e *Executor[T, Y]) Add(data ...Data[T, Y]) { e.list = append(e.list, data...) } func (e *Executor[T, Y]) Run(t *testing.T, do func(T) Y) { if do == nil { panic("execution body is nil") return } for _, v := range e.list { t.Run(v.Name, func(t *testing.T) { inner := do e.equalFn(t, v.Want, inner(v.Input)) }) } } func (e *Executor[T, Y]) RunE(t *testing.T, do func(T) (Y, error)) { if do == nil { panic("execution body is nil") return } for _, v := range e.list { t.Run(v.Name, func(t *testing.T) { inner := do got, err := inner(v.Input) if v.E != nil { assert.Equal(t, v.E, err) return } e.equalFn(t, v.Want, got) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/test/test_test.go
tools/goctl/test/test_test.go
package test import ( "errors" "strings" "testing" "github.com/stretchr/testify/assert" ) func TestExecutor_Run(t *testing.T) { executor := NewExecutor[string, string]() executor.Add([]Data[string, string]{ { Name: "empty", }, { Name: "snake_case", Input: "A_B_C", Want: "a_b_c", }, { Name: "camel_case", Input: "AaBbCc", Want: "aabbcc", }, }...) executor.Run(t, func(s string) string { return strings.ToLower(s) }) } func TestExecutor_RunE(t *testing.T) { var dummyError = errors.New("dummy error") executor := NewExecutor[string, string]() executor.Add([]Data[string, string]{ { Name: "empty", }, { Name: "snake_case", Input: "A_B_C", Want: "a_b_c", }, { Name: "camel_case", Input: "AaBbCc", Want: "aabbcc", }, { Name: "invalid_input", Input: "😄", E: dummyError, }, }...) executor.RunE(t, func(s string) (string, error) { for _, r := range s { if r == '_' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' { continue } return "", dummyError } return strings.ToLower(s), nil }) } func TestWithComparison(t *testing.T) { var dummyError = errors.New("dummy error") executor := NewExecutor[string, string](WithComparison[string, string](func(t *testing.T, expected, actual string) bool { return assert.Equal(t, expected, actual) })) executor.Add([]Data[string, string]{ { Name: "empty", }, { Name: "snake_case", Input: "A_B_C", Want: "a_b_c", }, { Name: "camel_case", Input: "AaBbCc", Want: "aabbcc", }, { Name: "invalid_input", Input: "😄", E: dummyError, }, }...) executor.RunE(t, func(s string) (string, error) { for _, r := range s { if r == '_' || r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' { continue } return "", dummyError } return strings.ToLower(s), nil }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/gateway/cmd.go
tools/goctl/gateway/cmd.go
package gateway import ( _ "embed" "os" "path/filepath" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax" "github.com/zeromicro/go-zero/tools/goctl/util/ctx" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) var ( varStringHome string varStringRemote string varStringBranch string varStringDir string Cmd = cobrax.NewCommand("gateway", cobrax.WithRunE(generateGateway)) ) func init() { Cmd.PersistentFlags().StringVar(&varStringHome, "home") Cmd.PersistentFlags().StringVar(&varStringRemote, "remote") Cmd.PersistentFlags().StringVar(&varStringBranch, "branch") Cmd.PersistentFlags().StringVar(&varStringDir, "dir") } func generateGateway(*cobra.Command, []string) error { if err := pathx.MkdirIfNotExist(varStringDir); err != nil { return err } if _, err := ctx.Prepare(varStringDir); err != nil { return err } etcContent, err := pathx.LoadTemplate(category, etcTemplateFileFile, etcTemplate) if err != nil { return err } mainContent, err := pathx.LoadTemplate(category, mainTemplateFile, mainTemplate) if err != nil { return err } etcDir := filepath.Join(varStringDir, "etc") if err := pathx.MkdirIfNotExist(etcDir); err != nil { return err } etcFile := filepath.Join(etcDir, "gateway.yaml") if err := os.WriteFile(etcFile, []byte(etcContent), 0644); err != nil { return err } mainFile := filepath.Join(varStringDir, "main.go") return os.WriteFile(mainFile, []byte(mainContent), 0644) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/gateway/template.go
tools/goctl/gateway/template.go
package gateway import ( _ "embed" "fmt" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const ( category = "gateway" etcTemplateFileFile = "etc.tpl" mainTemplateFile = "main.tpl" ) //go:embed conf.yml var etcTemplate string //go:embed gateway.tpl var mainTemplate string var templates = map[string]string{ etcTemplateFileFile: etcTemplate, mainTemplateFile: mainTemplate, } // GenTemplates is the entry for command goctl template, // it will create the specified category func GenTemplates() error { return pathx.InitTemplates(category, templates) } // RevertTemplate restores the deleted template files func RevertTemplate(name string) error { content, ok := templates[name] if !ok { return fmt.Errorf("%s: no such file name", name) } return pathx.CreateTemplate(category, name, content) } // Clean deletes all template files func Clean() error { return pathx.Clean(category) } // Update is used to update the template files, it will delete the existing old templates at first, // and then create the latest template files func Update() error { err := Clean() if err != nil { return err } return pathx.InitTemplates(category, templates) } // Category returns a const string value for rpc template category func Category() string { return category }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/cmd.go
tools/goctl/api/cmd.go
package api import ( "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/api/apigen" "github.com/zeromicro/go-zero/tools/goctl/api/dartgen" "github.com/zeromicro/go-zero/tools/goctl/api/docgen" "github.com/zeromicro/go-zero/tools/goctl/api/format" "github.com/zeromicro/go-zero/tools/goctl/api/gogen" "github.com/zeromicro/go-zero/tools/goctl/api/javagen" "github.com/zeromicro/go-zero/tools/goctl/api/ktgen" "github.com/zeromicro/go-zero/tools/goctl/api/new" "github.com/zeromicro/go-zero/tools/goctl/api/swagger" "github.com/zeromicro/go-zero/tools/goctl/api/tsgen" "github.com/zeromicro/go-zero/tools/goctl/api/validate" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/cobrax" "github.com/zeromicro/go-zero/tools/goctl/plugin" ) var ( // Cmd describes an api command. Cmd = cobrax.NewCommand("api", cobrax.WithRunE(apigen.CreateApiTemplate)) dartCmd = cobrax.NewCommand("dart", cobrax.WithRunE(dartgen.DartCommand)) docCmd = cobrax.NewCommand("doc", cobrax.WithRunE(docgen.DocCommand)) formatCmd = cobrax.NewCommand("format", cobrax.WithRunE(format.GoFormatApi)) goCmd = cobrax.NewCommand("go", cobrax.WithRunE(gogen.GoCommand)) newCmd = cobrax.NewCommand("new", cobrax.WithRunE(new.CreateServiceCommand), cobrax.WithArgs(cobra.MatchAll(cobra.ExactArgs(1), cobra.OnlyValidArgs))) validateCmd = cobrax.NewCommand("validate", cobrax.WithRunE(validate.GoValidateApi)) javaCmd = cobrax.NewCommand("java", cobrax.WithRunE(javagen.JavaCommand), cobrax.WithHidden()) ktCmd = cobrax.NewCommand("kt", cobrax.WithRunE(ktgen.KtCommand)) pluginCmd = cobrax.NewCommand("plugin", cobrax.WithRunE(plugin.PluginCommand)) tsCmd = cobrax.NewCommand("ts", cobrax.WithRunE(tsgen.TsCommand)) swaggerCmd = cobrax.NewCommand("swagger", cobrax.WithRunE(swagger.Command)) ) func init() { var ( apiCmdFlags = Cmd.Flags() dartCmdFlags = dartCmd.Flags() docCmdFlags = docCmd.Flags() formatCmdFlags = formatCmd.Flags() goCmdFlags = goCmd.Flags() javaCmdFlags = javaCmd.Flags() ktCmdFlags = ktCmd.Flags() newCmdFlags = newCmd.Flags() pluginCmdFlags = pluginCmd.Flags() tsCmdFlags = tsCmd.Flags() validateCmdFlags = validateCmd.Flags() swaggerCmdFlags = swaggerCmd.Flags() ) apiCmdFlags.StringVar(&apigen.VarStringOutput, "o") apiCmdFlags.StringVar(&apigen.VarStringHome, "home") apiCmdFlags.StringVar(&apigen.VarStringRemote, "remote") apiCmdFlags.StringVar(&apigen.VarStringBranch, "branch") dartCmdFlags.StringVar(&dartgen.VarStringDir, "dir") dartCmdFlags.StringVar(&dartgen.VarStringAPI, "api") dartCmdFlags.BoolVar(&dartgen.VarStringLegacy, "legacy") dartCmdFlags.StringVar(&dartgen.VarStringHostname, "hostname") dartCmdFlags.StringVar(&dartgen.VarStringScheme, "scheme") docCmdFlags.StringVar(&docgen.VarStringDir, "dir") docCmdFlags.StringVar(&docgen.VarStringOutput, "o") formatCmdFlags.StringVar(&format.VarStringDir, "dir") formatCmdFlags.BoolVar(&format.VarBoolIgnore, "iu") formatCmdFlags.BoolVar(&format.VarBoolUseStdin, "stdin") formatCmdFlags.BoolVar(&format.VarBoolSkipCheckDeclare, "declare") goCmdFlags.StringVar(&gogen.VarStringDir, "dir") goCmdFlags.StringVar(&gogen.VarStringAPI, "api") goCmdFlags.StringVar(&gogen.VarStringHome, "home") goCmdFlags.StringVar(&gogen.VarStringRemote, "remote") goCmdFlags.StringVar(&gogen.VarStringBranch, "branch") goCmdFlags.BoolVar(&gogen.VarBoolWithTest, "test") goCmdFlags.BoolVar(&gogen.VarBoolTypeGroup, "type-group") goCmdFlags.StringVarWithDefaultValue(&gogen.VarStringStyle, "style", config.DefaultFormat) javaCmdFlags.StringVar(&javagen.VarStringDir, "dir") javaCmdFlags.StringVar(&javagen.VarStringAPI, "api") ktCmdFlags.StringVar(&ktgen.VarStringDir, "dir") ktCmdFlags.StringVar(&ktgen.VarStringAPI, "api") ktCmdFlags.StringVar(&ktgen.VarStringPKG, "pkg") newCmdFlags.StringVar(&new.VarStringHome, "home") newCmdFlags.StringVar(&new.VarStringRemote, "remote") newCmdFlags.StringVar(&new.VarStringBranch, "branch") newCmdFlags.StringVar(&new.VarStringModule, "module") newCmdFlags.StringVarWithDefaultValue(&new.VarStringStyle, "style", config.DefaultFormat) pluginCmdFlags.StringVarP(&plugin.VarStringPlugin, "plugin", "p") pluginCmdFlags.StringVar(&plugin.VarStringDir, "dir") pluginCmdFlags.StringVar(&plugin.VarStringAPI, "api") pluginCmdFlags.StringVar(&plugin.VarStringStyle, "style") tsCmdFlags.StringVar(&tsgen.VarStringDir, "dir") tsCmdFlags.StringVar(&tsgen.VarStringAPI, "api") tsCmdFlags.StringVar(&tsgen.VarStringCaller, "caller") tsCmdFlags.BoolVar(&tsgen.VarBoolUnWrap, "unwrap") swaggerCmdFlags.StringVar(&swagger.VarStringAPI, "api") swaggerCmdFlags.StringVar(&swagger.VarStringDir, "dir") swaggerCmdFlags.StringVar(&swagger.VarStringFilename, "filename") swaggerCmdFlags.BoolVar(&swagger.VarBoolYaml, "yaml") validateCmdFlags.StringVar(&validate.VarStringAPI, "api") // Add sub-commands Cmd.AddCommand(dartCmd, docCmd, formatCmd, goCmd, javaCmd, ktCmd, newCmd, pluginCmd, tsCmd, validateCmd, swaggerCmd) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/util/util.go
tools/goctl/api/util/util.go
package util import ( "errors" "fmt" "io" "os" "path" "strings" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) // MaybeCreateFile creates file if not exists func MaybeCreateFile(dir, subdir, file string) (fp *os.File, created bool, err error) { logx.Must(pathx.MkdirIfNotExist(path.Join(dir, subdir))) fpath := path.Join(dir, subdir, file) if pathx.FileExists(fpath) { fmt.Printf("%s exists, ignored generation\n", fpath) return nil, false, nil } fp, err = pathx.CreateIfNotExist(fpath) created = err == nil return } // WrapErr wraps an error with message func WrapErr(err error, message string) error { return errors.New(message + ", " + err.Error()) } // Copy calls io.Copy if the source file and destination file exists func Copy(src, dst string) (int64, error) { sourceFileStat, err := os.Stat(src) if err != nil { return 0, err } if !sourceFileStat.Mode().IsRegular() { return 0, fmt.Errorf("%s is not a regular file", src) } source, err := os.Open(src) if err != nil { return 0, err } defer source.Close() destination, err := os.Create(dst) if err != nil { return 0, err } defer destination.Close() nBytes, err := io.Copy(destination, source) return nBytes, err } // ComponentName returns component name for typescript func ComponentName(api *spec.ApiSpec) string { name := api.Service.Name if strings.HasSuffix(name, "-api") { return name[:len(name)-4] + "Components" } return name + "Components" } // WriteIndent writes tab spaces func WriteIndent(writer io.Writer, indent int) { for i := 0; i < indent; i++ { fmt.Fprint(writer, "\t") } } // RemoveComment filters comment content func RemoveComment(line string) string { commentIdx := strings.Index(line, "//") if commentIdx >= 0 { return strings.TrimSpace(line[:commentIdx]) } return strings.TrimSpace(line) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/util/case.go
tools/goctl/api/util/case.go
package util import ( "strings" "unicode" ) // IsUpperCase returns true if the rune in A-Z func IsUpperCase(r rune) bool { if r >= 'A' && r <= 'Z' { return true } return false } // IsLowerCase returns true if the rune in a-z func IsLowerCase(r rune) bool { if r >= 'a' && r <= 'z' { return true } return false } // ToSnakeCase returns a copy string by converting camel case into snake case func ToSnakeCase(s string) string { var out []rune for index, r := range s { if index == 0 { out = append(out, ToLowerCase(r)) continue } if IsUpperCase(r) && index != 0 { if IsLowerCase(rune(s[index-1])) { out = append(out, '_', ToLowerCase(r)) continue } if index < len(s)-1 && IsLowerCase(rune(s[index+1])) { out = append(out, '_', ToLowerCase(r)) continue } out = append(out, ToLowerCase(r)) continue } out = append(out, r) } return string(out) } // ToCamelCase returns a copy string by converting snake case into camel case func ToCamelCase(s string) string { s = ToLower(s) out := []rune{} for index, r := range s { if r == '_' { continue } if index == 0 { out = append(out, ToUpperCase(r)) continue } if index > 0 && s[index-1] == '_' { out = append(out, ToUpperCase(r)) continue } out = append(out, r) } return string(out) } // ToLowerCase converts rune into lower case func ToLowerCase(r rune) rune { dx := 'A' - 'a' if IsUpperCase(r) { return r - dx } return r } // ToUpperCase converts rune into upper case func ToUpperCase(r rune) rune { dx := 'A' - 'a' if IsLowerCase(r) { return r + dx } return r } // ToLower returns a copy string by converting it into lower func ToLower(s string) string { out := make([]rune, 0, len(s)) for _, r := range s { out = append(out, ToLowerCase(r)) } return string(out) } // ToUpper returns a copy string by converting it into upper func ToUpper(s string) string { out := make([]rune, 0, len(s)) for _, r := range s { out = append(out, ToUpperCase(r)) } return string(out) } // UpperFirst converts s[0] into upper case func UpperFirst(s string) string { if len(s) == 0 { return s } return ToUpper(s[:1]) + s[1:] } // UnExport converts the first letter into lower case func UnExport(text string) bool { var flag bool str := strings.Map(func(r rune) rune { if flag { return r } if unicode.IsLetter(r) { flag = true return unicode.ToLower(r) } return r }, text) return str == text }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/new/newservice.go
tools/goctl/api/new/newservice.go
package new import ( _ "embed" "errors" "html/template" "os" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/api/gogen" conf "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) //go:embed api.tpl var apiTemplate string var ( // VarStringHome describes the goctl home. VarStringHome string // VarStringRemote describes the remote git repository. VarStringRemote string // VarStringBranch describes the git branch. VarStringBranch string // VarStringStyle describes the style of output files. VarStringStyle string // VarStringModule describes the module name for go.mod. VarStringModule string ) // CreateServiceCommand fast create service func CreateServiceCommand(_ *cobra.Command, args []string) error { dirName := args[0] if len(VarStringStyle) == 0 { VarStringStyle = conf.DefaultFormat } if strings.Contains(dirName, "-") { return errors.New("api new command service name not support strikethrough, because this will used by function name") } abs, err := filepath.Abs(dirName) if err != nil { return err } err = pathx.MkdirIfNotExist(abs) if err != nil { return err } dirName = filepath.Base(filepath.Clean(abs)) filename := dirName + ".api" apiFilePath := filepath.Join(abs, filename) fp, err := os.Create(apiFilePath) if err != nil { return err } defer fp.Close() if len(VarStringRemote) > 0 { repo, _ := util.CloneIntoGitHome(VarStringRemote, VarStringBranch) if len(repo) > 0 { VarStringHome = repo } } if len(VarStringHome) > 0 { pathx.RegisterGoctlHome(VarStringHome) } text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate) if err != nil { return err } t := template.Must(template.New("template").Parse(text)) if err := t.Execute(fp, map[string]string{ "name": dirName, "handler": strings.Title(dirName), }); err != nil { return err } err = gogen.DoGenProjectWithModule(apiFilePath, abs, VarStringModule, VarStringStyle, false) return err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/new/newservice_test.go
tools/goctl/api/new/newservice_test.go
package new import ( "os" "path/filepath" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zeromicro/go-zero/tools/goctl/api/gogen" "github.com/zeromicro/go-zero/tools/goctl/config" ) func TestDoGenProjectWithModule_Integration(t *testing.T) { tests := []struct { name string moduleName string serviceName string expectedMod string }{ { name: "with custom module", moduleName: "github.com/test/customapi", serviceName: "myservice", expectedMod: "github.com/test/customapi", }, { name: "with empty module", moduleName: "", serviceName: "myservice", expectedMod: "myservice", }, { name: "with simple module", moduleName: "simpleapi", serviceName: "testapi", expectedMod: "simpleapi", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Create temporary directory tempDir, err := os.MkdirTemp("", "goctl-api-module-test-*") require.NoError(t, err) defer os.RemoveAll(tempDir) // Create service directory serviceDir := filepath.Join(tempDir, tt.serviceName) err = os.MkdirAll(serviceDir, 0755) require.NoError(t, err) // Create a simple API file for testing apiContent := `syntax = "v1" type Request { Name string ` + "`" + `path:"name,options=you|me"` + "`" + ` } type Response { Message string ` + "`" + `json:"message"` + "`" + ` } service ` + tt.serviceName + `-api { @handler ` + tt.serviceName + `Handler get /from/:name(Request) returns (Response) } ` apiFile := filepath.Join(serviceDir, tt.serviceName+".api") err = os.WriteFile(apiFile, []byte(apiContent), 0644) require.NoError(t, err) // Call the module-aware service creation function err = gogen.DoGenProjectWithModule(apiFile, serviceDir, tt.moduleName, config.DefaultFormat, false) assert.NoError(t, err) // Check go.mod file goModPath := filepath.Join(serviceDir, "go.mod") assert.FileExists(t, goModPath) // Verify module name in go.mod content, err := os.ReadFile(goModPath) require.NoError(t, err) assert.Contains(t, string(content), "module "+tt.expectedMod) // Check basic directory structure was created assert.DirExists(t, filepath.Join(serviceDir, "etc")) assert.DirExists(t, filepath.Join(serviceDir, "internal")) assert.DirExists(t, filepath.Join(serviceDir, "internal", "handler")) assert.DirExists(t, filepath.Join(serviceDir, "internal", "logic")) assert.DirExists(t, filepath.Join(serviceDir, "internal", "svc")) assert.DirExists(t, filepath.Join(serviceDir, "internal", "types")) assert.DirExists(t, filepath.Join(serviceDir, "internal", "config")) // Check that main.go imports use correct module mainGoPath := filepath.Join(serviceDir, tt.serviceName+".go") if _, err := os.Stat(mainGoPath); err == nil { mainContent, err := os.ReadFile(mainGoPath) require.NoError(t, err) // Check for import of internal packages with correct module path assert.Contains(t, string(mainContent), `"`+tt.expectedMod+"/internal/") } }) } } func TestCreateServiceCommand_Integration(t *testing.T) { tests := []struct { name string moduleName string serviceName string expectedMod string shouldError bool }{ { name: "valid service with custom module", moduleName: "github.com/example/testapi", serviceName: "myapi", expectedMod: "github.com/example/testapi", shouldError: false, }, { name: "valid service with no module", moduleName: "", serviceName: "simpleapi", expectedMod: "simpleapi", shouldError: false, }, { name: "invalid service name with hyphens", moduleName: "github.com/test/api", serviceName: "my-api", expectedMod: "", shouldError: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.shouldError && tt.serviceName == "my-api" { // Test that service names with hyphens are rejected // This is tested in the actual command function, not the generate function assert.Contains(t, tt.serviceName, "-") return } // Create temporary directory tempDir, err := os.MkdirTemp("", "goctl-create-service-test-*") require.NoError(t, err) defer os.RemoveAll(tempDir) // Change to temp directory oldDir, _ := os.Getwd() defer os.Chdir(oldDir) os.Chdir(tempDir) // Set the module variable as the command would VarStringModule = tt.moduleName VarStringStyle = config.DefaultFormat // Create the service directory manually since we're testing the core functionality serviceDir := filepath.Join(tempDir, tt.serviceName) // Simulate what CreateServiceCommand does - create API file and call DoGenProjectWithModule err = os.MkdirAll(serviceDir, 0755) require.NoError(t, err) // Create API file apiContent := `syntax = "v1" type Request { Name string ` + "`" + `path:"name,options=you|me"` + "`" + ` } type Response { Message string ` + "`" + `json:"message"` + "`" + ` } service ` + tt.serviceName + `-api { @handler ` + tt.serviceName + `Handler get /from/:name(Request) returns (Response) } ` apiFile := filepath.Join(serviceDir, tt.serviceName+".api") err = os.WriteFile(apiFile, []byte(apiContent), 0644) require.NoError(t, err) // Call DoGenProjectWithModule as CreateServiceCommand does err = gogen.DoGenProjectWithModule(apiFile, serviceDir, VarStringModule, VarStringStyle, false) if tt.shouldError { assert.Error(t, err) } else { assert.NoError(t, err) // Verify go.mod goModPath := filepath.Join(serviceDir, "go.mod") assert.FileExists(t, goModPath) content, err := os.ReadFile(goModPath) require.NoError(t, err) assert.Contains(t, string(content), "module "+tt.expectedMod) } }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/new/template.go
tools/goctl/api/new/template.go
package new import ( "fmt" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const ( category = "newapi" apiTemplateFile = "newtemplate.tpl" ) var templates = map[string]string{ apiTemplateFile: apiTemplate, } // Category returns the category of the api files. func Category() string { return category } // Clean cleans the generated deployment files. func Clean() error { return pathx.Clean(category) } // GenTemplates generates api template files. func GenTemplates() error { return pathx.InitTemplates(category, templates) } // RevertTemplate reverts the given template file to the default value. func RevertTemplate(name string) error { content, ok := templates[name] if !ok { return fmt.Errorf("%s: no such file name", name) } return pathx.CreateTemplate(category, name, content) } // Update updates the template files to the templates built in current goctl. func Update() error { err := Clean() if err != nil { return err } return pathx.InitTemplates(category, templates) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/genapi.go
tools/goctl/api/dartgen/genapi.go
package dartgen import ( "os" "strings" "text/template" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) const apiTemplate = `import 'api.dart'; import '../data/{{with .Info}}{{getBaseName .Title}}{{end}}.dart'; {{with .Service}} /// {{.Name}} {{range .Routes}} /// --{{.Path}}-- /// /// request: {{with .RequestType}}{{.Name}}{{end}} /// response: {{with .ResponseType}}{{.Name}}{{end}} Future {{pathToFuncName .Path}}( {{if ne .Method "get"}}{{with .RequestType}}{{.Name}} request,{{end}}{{end}} {Function({{with .ResponseType}}{{.Name}}{{end}}) ok, Function(String) fail, Function eventually}) async { await api{{if eq .Method "get"}}Get{{else}}Post{{end}}('{{.Path}}',{{if ne .Method "get"}}request,{{end}} ok: (data) { if (ok != null) ok({{with .ResponseType}}{{.Name}}.fromJson(data){{end}}); }, fail: fail, eventually: eventually); } {{end}} {{end}}` const apiTemplateV2 = `import 'api.dart'; import '../data/{{with .Service}}{{.Name}}{{end}}.dart'; {{with .Service}} /// {{.Name}} {{range $i, $Route := .Routes}} /// --{{.Path}}-- /// /// request: {{with .RequestType}}{{.Name}}{{end}} /// response: {{with .ResponseType}}{{.Name}}{{end}} Future {{normalizeHandlerName .Handler}}( {{if hasUrlPathParams $Route}}{{extractPositionalParamsFromPath $Route}},{{end}} {{if ne .Method "get"}}{{with .RequestType}}{{.Name}} request,{{end}}{{end}} {Function({{with .ResponseType}}{{.Name}}{{end}})? ok, Function(String)? fail, Function? eventually}) async { await api{{if eq .Method "get"}}Get{{else}}Post{{end}}({{makeDartRequestUrlPath $Route}},{{if ne .Method "get"}}request,{{end}} ok: (data) { if (ok != null) ok({{with .ResponseType}}{{.Name}}.fromJson(data){{end}}); }, fail: fail, eventually: eventually); } {{end}} {{end}}` func genApi(dir string, api *spec.ApiSpec, isLegacy bool) error { err := os.MkdirAll(dir, 0o755) if err != nil { return err } err = genApiFile(dir, isLegacy) if err != nil { return err } file, err := os.OpenFile(dir+strings.ToLower(api.Service.Name+".dart"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } defer file.Close() t := template.New("apiTemplate") t = t.Funcs(funcMap) tpl := apiTemplateV2 if isLegacy { tpl = apiTemplate } t, err = t.Parse(tpl) if err != nil { return err } return t.Execute(file, api) } func genApiFile(dir string, isLegacy bool) error { path := dir + "api.dart" if fileExists(path) { return nil } apiFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } defer apiFile.Close() tpl := apiFileContentV2 if isLegacy { tpl = apiFileContent } _, err = apiFile.WriteString(tpl) return err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/genvars.go
tools/goctl/api/dartgen/genvars.go
package dartgen import ( "fmt" "os" ) const ( varTemplate = `import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../data/tokens.dart'; /// store tokens to local /// /// pass null will clean local stored tokens /// returns true if success, otherwise false Future<bool> setTokens(Tokens tokens) async { var sp = await SharedPreferences.getInstance(); if (tokens == null) { sp.remove('tokens'); return true; } return await sp.setString('tokens', jsonEncode(tokens.toJson())); } /// get local stored tokens /// /// if no, returns null Future<Tokens> getTokens() async { try { var sp = await SharedPreferences.getInstance(); var str = sp.getString('tokens'); if (str == null || str.isEmpty) { return null; } return Tokens.fromJson(jsonDecode(str)); } catch (e) { print(e); return null; } } ` varTemplateV2 = `import 'dart:convert'; import 'package:shared_preferences/shared_preferences.dart'; import '../data/tokens.dart'; const String _tokenKey = 'tokens'; /// Saves tokens Future<bool> setTokens(Tokens tokens) async { var sp = await SharedPreferences.getInstance(); return await sp.setString(_tokenKey, jsonEncode(tokens.toJson())); } /// remove tokens Future<bool> removeTokens() async { var sp = await SharedPreferences.getInstance(); return sp.remove(_tokenKey); } /// Reads tokens Future<Tokens?> getTokens() async { try { var sp = await SharedPreferences.getInstance(); var str = sp.getString('tokens'); if (str == null || str.isEmpty) { return null; } return Tokens.fromJson(jsonDecode(str)); } catch (e) { print(e); return null; } }` ) func genVars(dir string, isLegacy bool, scheme string, hostname string) error { err := os.MkdirAll(dir, 0o755) if err != nil { return err } if !fileExists(dir + "vars.dart") { err = os.WriteFile(dir+"vars.dart", []byte(fmt.Sprintf(`const serverHost='%s://%s';`, scheme, hostname)), 0o644) if err != nil { return err } } if !fileExists(dir + "kv.dart") { tpl := varTemplateV2 if isLegacy { tpl = varTemplate } err = os.WriteFile(dir+"kv.dart", []byte(tpl), 0o644) if err != nil { return err } } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/gen.go
tools/goctl/api/dartgen/gen.go
package dartgen import ( "errors" "fmt" "strings" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/tools/goctl/api/parser" ) var ( // VarStringDir describes the directory. VarStringDir string // VarStringAPI defines the API. VarStringAPI string // VarStringLegacy describes whether legacy. VarStringLegacy bool // VarStringHostname defines the hostname. VarStringHostname string // VarStringSchema defines the scheme. VarStringScheme string ) // DartCommand create dart network request code func DartCommand(_ *cobra.Command, _ []string) error { apiFile := VarStringAPI dir := VarStringDir isLegacy := VarStringLegacy hostname := VarStringHostname scheme := VarStringScheme if len(apiFile) == 0 { return errors.New("missing -api") } if len(dir) == 0 { return errors.New("missing -dir") } if len(hostname) == 0 { fmt.Println("you could use '-hostname' flag to specify your server hostname") hostname = "go-zero.dev" } if len(scheme) == 0 { fmt.Println("you could use '-scheme' flag to specify your server scheme") scheme = "http" } api, err := parser.Parse(apiFile) if err != nil { return err } if err := api.Validate(); err != nil { return err } api.Service = api.Service.JoinPrefix() if !strings.HasSuffix(dir, "/") { dir = dir + "/" } api.Info.Title = strings.Replace(apiFile, ".api", "", -1) logx.Must(genData(dir+"data/", api, isLegacy)) logx.Must(genApi(dir+"api/", api, isLegacy)) logx.Must(genVars(dir+"vars/", isLegacy, scheme, hostname)) if err := formatDir(dir); err != nil { logx.Errorf("failed to format, %v", err) } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/util.go
tools/goctl/api/dartgen/util.go
package dartgen import ( "errors" "fmt" "os" "path" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/api/util" ) const ( formTagKey = "form" pathTagKey = "path" headerTagKey = "header" ) func normalizeHandlerName(handlerName string) string { handler := strings.Replace(handlerName, "Handler", "", 1) handler = lowCamelCase(handler) return handler } func lowCamelCase(s string) string { if len(s) < 1 { return "" } s = util.ToCamelCase(util.ToSnakeCase(s)) return util.ToLower(s[:1]) + s[1:] } func getBaseName(str string) string { return path.Base(str) } func getPropertyFromMember(member spec.Member) string { name, err := member.GetPropertyName() if err != nil { panic(fmt.Sprintf("cannot get property name of %q", member.Name)) } return name } func isDirectType(s string) bool { return isAtomicType(s) || isListType(s) && isAtomicType(getCoreType(s)) } func isAtomicType(s string) bool { switch s { case "String", "int", "double", "bool": return true default: return false } } func isNumberType(s string) bool { switch s { case "int", "double": return true default: return false } } func isListType(s string) bool { return strings.HasPrefix(s, "List<") } func isClassListType(s string) bool { return isListType(s) && !isAtomicType(getCoreType(s)) } func isAtomicListType(s string) bool { return isListType(s) && isAtomicType(getCoreType(s)) } func isListItemsNullable(s string) bool { return isListType(s) && isNullableType(getCoreType(s)) } func isMapType(s string) bool { return strings.HasPrefix(s, "Map<") } // Only interface types are nullable func isNullableType(s string) bool { return strings.HasSuffix(s, "?") } func appendNullCoalescing(member spec.Member) string { if isNullableType(member.Type.Name()) { return "m['" + getPropertyFromMember(member) + "'] == null ? null : " } return "" } // To be compatible with omitempty tags in Golang // Only set default value for non-nullable types func appendDefaultEmptyValue(s string) string { if isNullableType(s) { return "" } if isAtomicType(s) { switch s { case "String": return `?? ""` case "int": return "?? 0" case "double": return "?? 0.0" case "bool": return "?? false" default: panic(errors.New("unknown atomic type")) } } if isListType(s) { return "?? []" } if isMapType(s) { return "?? {}" } return "" } func getCoreType(s string) string { if isAtomicType(s) { return s } if isListType(s) { s = strings.Replace(s, "List<", "", -1) return strings.Replace(s, ">", "", -1) } return s } func fileExists(path string) bool { _, err := os.Stat(path) return !os.IsNotExist(err) } func buildSpecType(tp spec.Type, name string) spec.Type { switch v := tp.(type) { case spec.PrimitiveType: return spec.PrimitiveType{RawName: name} case spec.MapType: return spec.MapType{RawName: name, Key: v.Key, Value: v.Value} case spec.ArrayType: return spec.ArrayType{RawName: name, Value: v.Value} case spec.InterfaceType: return spec.InterfaceType{RawName: name} case spec.PointerType: return spec.PointerType{RawName: name, Type: v.Type} } return tp } func specTypeToDart(tp spec.Type) (string, error) { switch v := tp.(type) { case spec.DefineStruct: return tp.Name(), nil case spec.PrimitiveType: r, ok := primitiveType(tp.Name()) if !ok { return "", errors.New("unsupported primitive type " + tp.Name()) } return r, nil case spec.MapType: valueType, err := specTypeToDart(v.Value) if err != nil { return "", err } return fmt.Sprintf("Map<String, %s>", valueType), nil case spec.ArrayType: if tp.Name() == "[]byte" { return "List<int>", nil } valueType, err := specTypeToDart(v.Value) if err != nil { return "", err } s := getBaseType(valueType) if len(s) != 0 { return s, nil } return fmt.Sprintf("List<%s>", valueType), nil case spec.InterfaceType: return "Object?", nil case spec.PointerType: valueType, err := specTypeToDart(v.Type) if err != nil { return "", err } return fmt.Sprintf("%s?", valueType), nil } return "", errors.New("unsupported primitive type " + tp.Name()) } func getBaseType(valueType string) string { switch valueType { case "int": return "List<int>" case "double": return "List<double>" case "boolean": return "List<bool>" case "String": return "List<String>" default: return "" } } func primitiveType(tp string) (string, bool) { switch tp { case "string": return "String", true case "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "rune": return "int", true case "float32", "float64": return "double", true case "bool": return "bool", true } return "", false } func hasUrlPathParams(route spec.Route) bool { ds, ok := route.RequestType.(spec.DefineStruct) if !ok { return false } return len(route.RequestTypeName()) > 0 && len(ds.GetTagMembers(pathTagKey)) > 0 } func extractPositionalParamsFromPath(route spec.Route) string { ds, ok := route.RequestType.(spec.DefineStruct) if !ok { return "" } tagMembers := ds.GetTagMembers(pathTagKey) params := make([]string, 0, len(tagMembers)) for _, member := range tagMembers { dartType := member.Type.Name() params = append(params, fmt.Sprintf("%s %s", dartType, getPropertyFromMember(member))) } return strings.Join(params, ", ") } func makeDartRequestUrlPath(route spec.Route) string { path := route.Path if route.RequestType == nil { return `"` + path + `"` } ds, ok := route.RequestType.(spec.DefineStruct) if !ok { return path } for _, member := range ds.GetTagMembers(pathTagKey) { paramName := member.Tags()[0].Name path = strings.ReplaceAll(path, ":"+paramName, "${"+getPropertyFromMember(member)+"}") } return `"` + path + `"` }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/format.go
tools/goctl/api/dartgen/format.go
package dartgen import ( "fmt" "os" "os/exec" ) const dartExec = "dart" func formatDir(dir string) error { ok, err := dirctoryExists(dir) if err != nil { return err } if !ok { return fmt.Errorf("format failed, directory %q does not exist", dir) } _, err = exec.LookPath(dartExec) if err != nil { return err } cmd := exec.Command(dartExec, "format", dir) cmd.Env = os.Environ() cmd.Stderr = os.Stderr return cmd.Run() } func dirctoryExists(dir string) (bool, error) { _, err := os.Stat(dir) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/gendata.go
tools/goctl/api/dartgen/gendata.go
package dartgen import ( "bytes" "os" "strings" "text/template" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) const dataTemplate = `// --{{with .APISpec.Info}}{{.Title}}{{end}}-- {{ range .APISpec.Types}} class {{.Name}}{ {{range .Members}} /// {{.Comment}} final {{if isNumberType .Type.Name}}num{{else}}{{.Type.Name}}{{end}} {{lowCamelCase .Name}}; {{end}} {{.Name}}({ {{range .Members}} this.{{lowCamelCase .Name}},{{end}} }); factory {{.Name}}.fromJson(Map<String,dynamic> m) { return {{.Name}}({{range .Members}} {{lowCamelCase .Name}}: {{if isDirectType .Type.Name}}m['{{getPropertyFromMember .}}']{{else if isClassListType .Type.Name}}(m['{{getPropertyFromMember .}}'] as List<dynamic>).map((i) => {{getCoreType .Type.Name}}.fromJson(i)){{else}}{{.Type.Name}}.fromJson(m['{{getPropertyFromMember .}}']){{end}},{{end}} ); } Map<String,dynamic> toJson() { return { {{range .Members}} '{{getPropertyFromMember .}}': {{if isDirectType .Type.Name}}{{lowCamelCase .Name}}{{else if isClassListType .Type.Name}}{{lowCamelCase .Name}}.map((i) => i.toJson()){{else}}{{lowCamelCase .Name}}.toJson(){{end}},{{end}} }; } {{ range $.InnerClassList}} {{.}} {{end}} } {{end}} ` const dataTemplateV2 = `// --{{with .APISpec.Info}}{{.Title}}{{end}}-- {{ range .APISpec.Types}} class {{.Name}} { {{range .Members}} {{if .Comment}}{{.Comment}}{{end}} final {{if isNumberType .Type.Name}}num{{else}}{{.Type.Name}}{{end}} {{lowCamelCase .Name}}; {{end}}{{.Name}}({{if .Members}}{ {{range .Members}} required this.{{lowCamelCase .Name}}, {{end}}}{{end}}); factory {{.Name}}.fromJson(Map<String,dynamic> m) { return {{.Name}}( {{range .Members}} {{lowCamelCase .Name}}: {{appendNullCoalescing .}} {{if isAtomicType .Type.Name}} m['{{getPropertyFromMember .}}'] {{appendDefaultEmptyValue .Type.Name}} {{else if isAtomicListType .Type.Name}} m['{{getPropertyFromMember .}}']?.cast<{{getCoreType .Type.Name}}>() {{appendDefaultEmptyValue .Type.Name}} {{else if isClassListType .Type.Name}} ((m['{{getPropertyFromMember .}}'] {{appendDefaultEmptyValue .Type.Name}}) as List<dynamic>).map((i) => {{getCoreType .Type.Name}}.fromJson(i)).toList() {{else if isMapType .Type.Name}} {{if isNumberType .Type.Name}}num{{else}}{{.Type.Name}}{{end}}.from(m['{{getPropertyFromMember .}}'] ?? {}) {{else}} {{.Type.Name}}.fromJson(m['{{getPropertyFromMember .}}']){{end}} ,{{end}} ); } Map<String,dynamic> toJson() { return { {{range .Members}} '{{getPropertyFromMember .}}': {{if isDirectType .Type.Name}} {{lowCamelCase .Name}} {{else if isMapType .Type.Name}} {{lowCamelCase .Name}} {{else if isClassListType .Type.Name}} {{lowCamelCase .Name}}{{if isNullableType .Type.Name}}?{{end}}.map((i) => i{{if isListItemsNullable .Type.Name}}?{{end}}.toJson()) {{else}} {{lowCamelCase .Name}}{{if isNullableType .Type.Name}}?{{end}}.toJson() {{end}} ,{{end}} }; } {{ range $.InnerClassList}} {{.}} {{end}} } {{end}}` type DartSpec struct { APISpec *spec.ApiSpec InnerClassList []string } func genData(dir string, api *spec.ApiSpec, isLegacy bool) error { err := os.MkdirAll(dir, 0o755) if err != nil { return err } err = genTokens(dir, isLegacy) if err != nil { return err } file, err := os.OpenFile(dir+strings.ToLower(api.Service.Name+".dart"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } defer file.Close() t := template.New("dataTemplate") t = t.Funcs(funcMap) tpl := dataTemplateV2 if isLegacy { tpl = dataTemplate } t, err = t.Parse(tpl) if err != nil { return err } err, dartSpec := convertDataType(api, isLegacy) if err != nil { return err } return t.Execute(file, dartSpec) } func genTokens(dir string, isLeagcy bool) error { path := dir + "tokens.dart" if fileExists(path) { return nil } tokensFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) if err != nil { return err } defer tokensFile.Close() tpl := tokensFileContentV2 if isLeagcy { tpl = tokensFileContent } _, err = tokensFile.WriteString(tpl) return err } func convertDataType(api *spec.ApiSpec, isLegacy bool) (error, *DartSpec) { var result DartSpec types := api.Types if len(types) == 0 { return nil, &result } for _, ty := range types { defineStruct, ok := ty.(spec.DefineStruct) if ok { for index, member := range defineStruct.Members { structMember, ok := member.Type.(spec.NestedStruct) if ok { defineStruct.Members[index].Type = spec.PrimitiveType{RawName: member.Name} t := template.New("dataTemplate") t = t.Funcs(funcMap) tpl := dataTemplateV2 if isLegacy { tpl = dataTemplate } t, err := t.Parse(tpl) if err != nil { return err, nil } var innerClassSpec = &spec.ApiSpec{ Types: []spec.Type{ spec.DefineStruct{ RawName: member.Name, Members: structMember.Members, }, }, } err, dartSpec := convertDataType(innerClassSpec, isLegacy) if err != nil { return err, nil } writer := bytes.NewBuffer(nil) err = t.Execute(writer, dartSpec) if err != nil { return err, nil } result.InnerClassList = append(result.InnerClassList, writer.String()) } else { tp, err := specTypeToDart(member.Type) if err != nil { return err, nil } defineStruct.Members[index].Type = buildSpecType(member.Type, tp) } } } } result.APISpec = api return nil, &result }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/vars.go
tools/goctl/api/dartgen/vars.go
package dartgen import "text/template" var funcMap = template.FuncMap{ "appendNullCoalescing": appendNullCoalescing, "appendDefaultEmptyValue": appendDefaultEmptyValue, "extractPositionalParamsFromPath": extractPositionalParamsFromPath, "getBaseName": getBaseName, "getCoreType": getCoreType, "getPropertyFromMember": getPropertyFromMember, "hasUrlPathParams": hasUrlPathParams, "isAtomicListType": isAtomicListType, "isAtomicType": isAtomicType, "isDirectType": isDirectType, "isClassListType": isClassListType, "isListItemsNullable": isListItemsNullable, "isMapType": isMapType, "isNullableType": isNullableType, "isNumberType": isNumberType, "lowCamelCase": lowCamelCase, "makeDartRequestUrlPath": makeDartRequestUrlPath, "normalizeHandlerName": normalizeHandlerName, } const ( apiFileContent = `import 'dart:io'; import 'dart:convert'; import '../vars/kv.dart'; import '../vars/vars.dart'; /// Send GET request. /// /// ok: the function that will be called on success. /// fail:the function that will be called on failure. /// eventually:the function that will be called regardless of success or failure. Future apiGet(String path, {Map<String, String> header, Function(Map<String, dynamic>) ok, Function(String) fail, Function eventually}) async { await _apiRequest('GET', path, null, header: header, ok: ok, fail: fail, eventually: eventually); } /// Send POST request. /// /// data: the data to post, it will be marshaled to json automatically. /// ok: the function that will be called on success. /// fail:the function that will be called on failure. /// eventually:the function that will be called regardless of success or failure. Future apiPost(String path, dynamic data, {Map<String, String> header, Function(Map<String, dynamic>) ok, Function(String) fail, Function eventually}) async { await _apiRequest('POST', path, data, header: header, ok: ok, fail: fail, eventually: eventually); } Future _apiRequest(String method, String path, dynamic data, {Map<String, String> header, Function(Map<String, dynamic>) ok, Function(String) fail, Function eventually}) async { var tokens = await getTokens(); try { var client = HttpClient(); HttpClientRequest r; if (method == 'POST') { r = await client.postUrl(Uri.parse(serverHost + path)); } else { r = await client.getUrl(Uri.parse(serverHost + path)); } var strData = ''; if (data != null) { strData = jsonEncode(data); } if (method == 'POST') { r.headers.set('Content-Type', 'application/json; charset=utf-8'); r.headers.set('Content-Length', utf8.encode(strData).length); } if (tokens != null) { r.headers.set('Authorization', tokens.accessToken); } if (header != null) { header.forEach((k, v) { r.headers.set(k, v); }); } r.write(strData); var rp = await r.close(); var body = await rp.transform(utf8.decoder).join(); print('${rp.statusCode} - $path'); print('-- request --'); print(strData); print('-- response --'); print('$body \n'); if (rp.statusCode == 404) { if (fail != null) fail('404 not found'); } else { Map<String, dynamic> base = jsonDecode(body); if (rp.statusCode == 200) { if (base['code'] != 0) { if (fail != null) fail(base['desc']); } else { if (ok != null) ok(base['data']); } } else if (base['code'] != 0) { if (fail != null) fail(base['desc']); } } } catch (e) { if (fail != null) fail(e.toString()); } if (eventually != null) eventually(); } ` apiFileContentV2 = `import 'dart:io'; import 'dart:convert'; import '../vars/kv.dart'; import '../vars/vars.dart'; /// send request with post method /// /// data: any request class that will be converted to json automatically /// ok: is called when request succeeds /// fail: is called when request fails /// eventually: is always called after the nearby function returns Future apiPost(String path, dynamic data, {Map<String, String>? header, Function(Map<String, dynamic>)? ok, Function(String)? fail, Function? eventually}) async { await _apiRequest('POST', path, data, header: header, ok: ok, fail: fail, eventually: eventually); } /// send request with get method /// /// ok: is called when request succeeds /// fail: is called when request fails /// eventually: is always called after the nearby function returns Future apiGet(String path, {Map<String, String>? header, Function(Map<String, dynamic>)? ok, Function(String)? fail, Function? eventually}) async { await _apiRequest('GET', path, null, header: header, ok: ok, fail: fail, eventually: eventually); } Future _apiRequest(String method, String path, dynamic data, {Map<String, String>? header, Function(Map<String, dynamic>)? ok, Function(String)? fail, Function? eventually}) async { var tokens = await getTokens(); try { var client = HttpClient(); HttpClientRequest r; if (method == 'POST') { r = await client.postUrl(Uri.parse(serverHost + path)); } else { r = await client.getUrl(Uri.parse(serverHost + path)); } var strData = ''; if (data != null) { strData = jsonEncode(data); } if (method == 'POST') { r.headers.set('Content-Type', 'application/json; charset=utf-8'); r.headers.set('Content-Length', utf8.encode(strData).length); } if (tokens != null) { r.headers.set('Authorization', tokens.accessToken); } if (header != null) { header.forEach((k, v) { r.headers.set(k, v); }); } r.write(strData); var rp = await r.close(); var body = await rp.transform(utf8.decoder).join(); print('${rp.statusCode} - $path'); print('-- request --'); print(strData); print('-- response --'); print('$body \n'); if (rp.statusCode == 404) { if (fail != null) fail('404 not found'); } else { Map<String, dynamic> base = jsonDecode(body); if (rp.statusCode == 200) { if (base['code'] != 0) { if (fail != null) fail(base['desc']); } else { if (ok != null) ok(base['data']); } } else if (base['code'] != 0) { if (fail != null) fail(base['desc']); } } } catch (e) { if (fail != null) fail(e.toString()); } if (eventually != null) eventually(); }` tokensFileContent = `class Tokens { /// the token used to access, it must be carried in the header of each request final String accessToken; final int accessExpire; /// the token used to refresh final String refreshToken; final int refreshExpire; final int refreshAfter; Tokens( {this.accessToken, this.accessExpire, this.refreshToken, this.refreshExpire, this.refreshAfter}); factory Tokens.fromJson(Map<String, dynamic> m) { return Tokens( accessToken: m['access_token'], accessExpire: m['access_expire'], refreshToken: m['refresh_token'], refreshExpire: m['refresh_expire'], refreshAfter: m['refresh_after']); } Map<String, dynamic> toJson() { return { 'access_token': accessToken, 'access_expire': accessExpire, 'refresh_token': refreshToken, 'refresh_expire': refreshExpire, 'refresh_after': refreshAfter, }; } } ` tokensFileContentV2 = `class Tokens { /// the token used to access, it must be carried in the header of each request final String accessToken; final int accessExpire; /// the token used to refresh final String refreshToken; final int refreshExpire; final int refreshAfter; Tokens({ required this.accessToken, required this.accessExpire, required this.refreshToken, required this.refreshExpire, required this.refreshAfter }); factory Tokens.fromJson(Map<String, dynamic> m) { return Tokens( accessToken: m['access_token'], accessExpire: m['access_expire'], refreshToken: m['refresh_token'], refreshExpire: m['refresh_expire'], refreshAfter: m['refresh_after']); } Map<String, dynamic> toJson() { return { 'access_token': accessToken, 'access_expire': accessExpire, 'refresh_token': refreshToken, 'refresh_expire': refreshExpire, 'refresh_after': refreshAfter, }; } } ` )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/dartgen/util_test.go
tools/goctl/api/dartgen/util_test.go
package dartgen import ( "testing" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func Test_getPropertyFromMember(t *testing.T) { tests := []struct { name string member spec.Member want string }{ { name: "json tag should be ok", member: spec.Member{ Tag: "`json:\"foo\"`", Name: "Foo", }, want: "foo", }, { name: "form tag should be ok", member: spec.Member{ Tag: "`form:\"bar\"`", Name: "Bar", }, want: "bar", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := getPropertyFromMember(tt.member); got != tt.want { t.Errorf("getPropertyFromMember() = %v, want %v", got, tt.want) } }) } } func Test_specTypeToDart(t *testing.T) { tests := []struct { name string specType spec.Type want string wantErr bool }{ { name: "[]string should return List<String>", specType: spec.ArrayType{RawName: "[]string", Value: spec.PrimitiveType{RawName: "string"}}, want: "List<String>", }, { name: "[]Foo should return List<Foo>", specType: spec.ArrayType{RawName: "[]Foo", Value: spec.DefineStruct{RawName: "Foo"}}, want: "List<Foo>", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := specTypeToDart(tt.specType) if (err != nil) != tt.wantErr { t.Errorf("specTypeToDart() error = %v, wantErr %v", err, tt.wantErr) return } if got != tt.want { t.Errorf("specTypeToDart() = %v, want %v", got, tt.want) } }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/ktgen/gen.go
tools/goctl/api/ktgen/gen.go
package ktgen import ( _ "embed" "fmt" "os" "path/filepath" "text/template" "github.com/iancoleman/strcase" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) var ( //go:embed apibase.tpl apiBaseTemplate string //go:embed api.tpl apiTemplate string ) func genBase(dir, pkg string, api *spec.ApiSpec) error { e := os.MkdirAll(dir, 0o755) if e != nil { return e } path := filepath.Join(dir, "BaseApi.kt") if _, e := os.Stat(path); e == nil { fmt.Println("BaseApi.kt already exists, skipped it.") return nil } file, e := os.OpenFile(path, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) if e != nil { return e } defer file.Close() t, e := template.New("n").Parse(apiBaseTemplate) if e != nil { return e } e = t.Execute(file, pkg) if e != nil { return e } return nil } func genApi(dir, pkg string, api *spec.ApiSpec) error { properties := api.Info.Properties if properties == nil { return fmt.Errorf("none properties") } title := properties["Title"] if len(title) == 0 { return fmt.Errorf("none title") } desc := properties["Desc"] if len(desc) == 0 { return fmt.Errorf("none desc") } name := strcase.ToCamel(title + "Api") path := filepath.Join(dir, name+".kt") api.Info.Title = name api.Info.Desc = desc e := os.MkdirAll(dir, 0o755) if e != nil { return e } file, e := os.OpenFile(path, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0o644) if e != nil { return e } defer file.Close() t, e := template.New("api").Funcs(funcsMap).Parse(apiTemplate) if e != nil { return e } type data struct { *spec.ApiSpec Pkg string } return t.Execute(file, data{api, pkg}) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/ktgen/cmd.go
tools/goctl/api/ktgen/cmd.go
package ktgen import ( "errors" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/api/parser" ) var ( // VarStringDir describes a directory. VarStringDir string // VarStringAPI describes an API. VarStringAPI string // VarStringPKG describes a package. VarStringPKG string ) // KtCommand generates kotlin code command entrance func KtCommand(_ *cobra.Command, _ []string) error { apiFile := VarStringAPI if apiFile == "" { return errors.New("missing -api") } dir := VarStringDir if dir == "" { return errors.New("missing -dir") } pkg := VarStringPKG if pkg == "" { return errors.New("missing -pkg") } api, e := parser.Parse(apiFile) if e != nil { return e } if err := api.Validate(); err != nil { return err } api.Service = api.Service.JoinPrefix() e = genBase(dir, pkg, api) if e != nil { return e } e = genApi(dir, pkg, api) if e != nil { return e } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/ktgen/funcs.go
tools/goctl/api/ktgen/funcs.go
package ktgen import ( "fmt" "log" "strings" "text/template" "github.com/iancoleman/strcase" "github.com/zeromicro/go-zero/tools/goctl/api/util" ) var funcsMap = template.FuncMap{ "lowCamelCase": lowCamelCase, "routeToFuncName": routeToFuncName, "parseType": parseType, "add": add, "upperCase": upperCase, } func lowCamelCase(s string) string { if len(s) < 1 { return "" } s = util.ToCamelCase(util.ToSnakeCase(s)) return util.ToLower(s[:1]) + s[1:] } func routeToFuncName(method, path string) string { if !strings.HasPrefix(path, "/") { path = "/" + path } path = strings.ReplaceAll(path, "/", "_") path = strings.ReplaceAll(path, "-", "_") path = strings.ReplaceAll(path, ":", "With_") return strings.ToLower(method) + strcase.ToCamel(path) } func parseType(t string) string { t = strings.Replace(t, "*", "", -1) if strings.HasPrefix(t, "[]") { return "List<" + parseType(t[2:]) + ">" } if strings.HasPrefix(t, "map") { tys, e := decomposeType(t) if e != nil { log.Fatal(e) } if len(tys) != 2 { log.Fatal("Map type number !=2") } return "Map<String," + parseType(tys[1]) + ">" } switch t { case "string": return "String" case "int", "int32", "int64": return "Int" case "float", "float32", "float64": return "Double" case "bool": return "Boolean" default: return t } } func decomposeType(t string) (result []string, err error) { add := func(tp string) error { ret, err := decomposeType(tp) if err != nil { return err } result = append(result, ret...) return nil } if strings.HasPrefix(t, "map") { t = strings.ReplaceAll(t, "map", "") if t[0] == '[' { pos := strings.Index(t, "]") if pos > 1 { if err = add(t[1:pos]); err != nil { return } if len(t) > pos+1 { err = add(t[pos+1:]) return } } } } else if strings.HasPrefix(t, "[]") { if len(t) > 2 { err = add(t[2:]) return } } else if strings.HasPrefix(t, "*") { err = add(t[1:]) return } else { result = append(result, t) return } err = fmt.Errorf("bad type %q", t) return } func add(a, i int) int { return a + i } func upperCase(s string) string { return strings.ToUpper(s) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/javagen/genpacket.go
tools/goctl/api/javagen/genpacket.go
package javagen import ( "bytes" _ "embed" "fmt" "strings" "text/template" "github.com/zeromicro/go-zero/core/stringx" "github.com/zeromicro/go-zero/tools/goctl/api/spec" apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util" "github.com/zeromicro/go-zero/tools/goctl/util" ) //go:embed packet.tpl var packetTemplate string func genPacket(dir, packetName string, api *spec.ApiSpec) error { for _, route := range api.Service.Routes() { if err := createWith(dir, api, route, packetName); err != nil { return err } } return nil } func createWith(dir string, api *spec.ApiSpec, route spec.Route, packetName string) error { packet := route.Handler packet = strings.Replace(packet, "Handler", "Packet", 1) packet = strings.Title(packet) if !strings.HasSuffix(packet, "Packet") { packet += "Packet" } javaFile := packet + ".java" fp, created, err := apiutil.MaybeCreateFile(dir, "", javaFile) if err != nil { return err } if !created { return nil } defer fp.Close() hasRequestBody := false if route.RequestType != nil { if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok { hasRequestBody = len(defineStruct.GetBodyMembers()) > 0 || len(defineStruct.GetFormMembers()) > 0 } } params := strings.TrimSpace(paramsForRoute(route)) if len(params) > 0 && hasRequestBody { params += ", " } paramsDeclaration := declarationForRoute(route) paramsSetter := paramsSet(route) imports := getImports(api, packetName) if len(route.ResponseTypeName()) == 0 { imports += fmt.Sprintf("\v%s", "import com.xhb.core.response.EmptyResponse;") } t := template.Must(template.New("packetTemplate").Parse(packetTemplate)) var tmplBytes bytes.Buffer err = t.Execute(&tmplBytes, map[string]any{ "packetName": packet, "method": strings.ToUpper(route.Method), "uri": processUri(route), "responseType": stringx.TakeOne(util.Title(route.ResponseTypeName()), "EmptyResponse"), "params": params, "paramsDeclaration": strings.TrimSpace(paramsDeclaration), "paramsSetter": paramsSetter, "packet": packetName, "requestType": util.Title(route.RequestTypeName()), "HasRequestBody": hasRequestBody, "imports": imports, "doc": doc(route), }) if err != nil { return err } _, err = fp.WriteString(formatSource(tmplBytes.String())) return err } func doc(route spec.Route) string { comment := route.JoinedDoc() if len(comment) > 0 { formatter := ` /* %s */` return fmt.Sprintf(formatter, comment) } return "" } func getImports(api *spec.ApiSpec, packetName string) string { var builder strings.Builder allTypes := api.Types if len(allTypes) > 0 { fmt.Fprintf(&builder, "import com.xhb.logic.http.packet.%s.model.*;\n", packetName) } return builder.String() } func paramsSet(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { param := cop[1:] builder.WriteString("\n") builder.WriteString(fmt.Sprintf("\t\tthis.%s = %s;", param, param)) } } result := builder.String() return result } func paramsForRoute(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { builder.WriteString(fmt.Sprintf("String %s, ", cop[1:])) } } return strings.TrimSuffix(builder.String(), ", ") } func declarationForRoute(route spec.Route) string { path := route.Path cops := strings.Split(path, "/") var builder strings.Builder writeIndent(&builder, 1) for _, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { writeIndent(&builder, 1) builder.WriteString(fmt.Sprintf("private String %s;\n", cop[1:])) } } result := strings.TrimSpace(builder.String()) if len(result) > 0 { result = "\n" + result } return result } func processUri(route spec.Route) string { path := route.Path var builder strings.Builder cops := strings.Split(path, "/") for index, cop := range cops { if len(cop) == 0 { continue } if strings.HasPrefix(cop, ":") { builder.WriteString("/\" + " + cop[1:] + " + \"") } else { builder.WriteString("/" + cop) if index == len(cops)-1 { builder.WriteString("\"") } } } result := strings.TrimSuffix(builder.String(), " + \"") if strings.HasPrefix(result, "/") { result = strings.TrimPrefix(result, "/") result = "\"" + result } return result + formString(route) } func formString(route spec.Route) string { var keyValues []string if defineStruct, ok := route.RequestType.(spec.DefineStruct); ok { forms := defineStruct.GetFormMembers() for _, item := range forms { name, err := item.GetPropertyName() if err != nil { panic(err) } strcat := "?" if len(keyValues) > 0 { strcat = "&" } if item.Type.Name() == "bool" { name = strings.TrimPrefix(name, "Is") name = strings.TrimPrefix(name, "is") keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.is%s()`, strcat, name, strings.Title(name))) } else { keyValues = append(keyValues, fmt.Sprintf(`"%s%s=" + request.get%s()`, strcat, name, strings.Title(name))) } } if len(keyValues) > 0 { return " + " + strings.Join(keyValues, " + ") } } return "" }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/javagen/gen.go
tools/goctl/api/javagen/gen.go
package javagen import ( "errors" "fmt" "strings" "github.com/gookit/color" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/tools/goctl/api/parser" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) var ( // VarStringDir describes a directory. VarStringDir string // VarStringAPI describes an API. VarStringAPI string ) // JavaCommand generates java code command entrance. func JavaCommand(_ *cobra.Command, _ []string) error { apiFile := VarStringAPI dir := VarStringDir if len(apiFile) == 0 { return errors.New("missing -api") } if len(dir) == 0 { return errors.New("missing -dir") } api, err := parser.Parse(apiFile) if err != nil { return err } if err := api.Validate(); err != nil { return err } api.Service = api.Service.JoinPrefix() packetName := strings.TrimSuffix(api.Service.Name, "-api") logx.Must(pathx.MkdirIfNotExist(dir)) logx.Must(genPacket(dir, packetName, api)) logx.Must(genComponents(dir, packetName, api)) fmt.Println(color.Green.Render("Done.")) return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/javagen/util.go
tools/goctl/api/javagen/util.go
package javagen import ( "errors" "fmt" "io" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) func writeProperty(writer io.Writer, member spec.Member, indent int) error { if len(member.Comment) > 0 { writeIndent(writer, indent) fmt.Fprint(writer, member.Comment+pathx.NL) } writeIndent(writer, indent) ty, err := specTypeToJava(member.Type) ty = strings.Replace(ty, "*", "", 1) if err != nil { return err } name, err := member.GetPropertyName() if err != nil { return err } _, err = fmt.Fprintf(writer, "private %s %s", ty, name) if err != nil { return err } err = writeDefaultValue(writer, member) if err != nil { return err } fmt.Fprint(writer, ";\n") return err } func writeDefaultValue(writer io.Writer, member spec.Member) error { javaType, err := specTypeToJava(member.Type) if err != nil { return err } if javaType == "String" { _, err := fmt.Fprintf(writer, " = \"\"") return err } return nil } func writeIndent(writer io.Writer, indent int) { for i := 0; i < indent; i++ { fmt.Fprint(writer, "\t") } } func indentString(indent int) string { result := "" for i := 0; i < indent; i++ { result += "\t" } return result } func specTypeToJava(tp spec.Type) (string, error) { switch v := tp.(type) { case spec.DefineStruct: return util.Title(tp.Name()), nil case spec.PrimitiveType: r, ok := primitiveType(tp.Name()) if !ok { return "", errors.New("unsupported primitive type " + tp.Name()) } return r, nil case spec.MapType: valueType, err := specTypeToJava(v.Value) if err != nil { return "", err } return fmt.Sprintf("java.util.HashMap<String, %s>", util.Title(valueType)), nil case spec.ArrayType: if tp.Name() == "[]byte" { return "byte[]", nil } valueType, err := specTypeToJava(v.Value) if err != nil { return "", err } s := getBaseType(valueType) if len(s) == 0 { return s, errors.New("unsupported primitive type " + tp.Name()) } return fmt.Sprintf("java.util.ArrayList<%s>", util.Title(valueType)), nil case spec.InterfaceType: return "Object", nil case spec.PointerType: return specTypeToJava(v.Type) } return "", errors.New("unsupported primitive type " + tp.Name()) } func getBaseType(valueType string) string { switch valueType { case "int": return "Integer[]" case "long": return "Long[]" case "float": return "Float[]" case "double": return "Double[]" case "boolean": return "Boolean[]" default: return "" } } func primitiveType(tp string) (string, bool) { switch tp { case "string": return "String", true case "int64", "uint64": return "long", true case "int", "int8", "int32", "uint", "uint8", "uint16", "uint32": return "int", true case "float", "float32": return "float", true case "float64": return "double", true case "bool": return "boolean", true } return "", false }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/javagen/gencomponents.go
tools/goctl/api/javagen/gencomponents.go
package javagen import ( "bufio" "bytes" _ "embed" "errors" "fmt" "io" "path" "slices" "strings" "text/template" "github.com/zeromicro/go-zero/tools/goctl/api/spec" apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const ( httpResponseData = "import com.xhb.core.response.HttpResponseData;" httpData = "import com.xhb.core.packet.HttpData;" ) var ( //go:embed component.tpl componentTemplate string //go:embed getset.tpl getSetTemplate string //go:embed bool.tpl boolTemplate string ) type componentsContext struct { api *spec.ApiSpec requestTypes []spec.Type responseTypes []spec.Type imports []string members []spec.Member } func genComponents(dir, packetName string, api *spec.ApiSpec) error { types := api.Types if len(types) == 0 { return nil } var requestTypes []spec.Type var responseTypes []spec.Type for _, group := range api.Service.Groups { for _, route := range group.Routes { if route.RequestType != nil { requestTypes = append(requestTypes, route.RequestType) } if route.ResponseType != nil { responseTypes = append(responseTypes, route.ResponseType) } } } context := componentsContext{api: api, requestTypes: requestTypes, responseTypes: responseTypes} for _, ty := range types { if err := context.createComponent(dir, packetName, ty); err != nil { return err } } return nil } func (c *componentsContext) createComponent(dir, packetName string, ty spec.Type) error { defineStruct, done, err := c.checkStruct(ty) if done { return err } modelFile := util.Title(ty.Name()) + ".java" filename := path.Join(dir, modelDir, modelFile) if err := pathx.RemoveOrQuit(filename); err != nil { return err } propertiesString, err := c.buildProperties(defineStruct) if err != nil { return err } getSetString, err := c.buildGetterSetter(defineStruct) if err != nil { return err } superClassName := "HttpData" for _, item := range c.responseTypes { if item.Name() == defineStruct.Name() { superClassName = "HttpResponseData" if !slices.Contains(c.imports, httpResponseData) { c.imports = append(c.imports, httpResponseData) } break } } if superClassName == "HttpData" && !slices.Contains(c.imports, httpData) { c.imports = append(c.imports, httpData) } params, constructorSetter, err := c.buildConstructor() if err != nil { return err } fp, created, err := apiutil.MaybeCreateFile(dir, modelDir, modelFile) if err != nil { return err } if !created { return nil } defer fp.Close() buffer := new(bytes.Buffer) t := template.Must(template.New("componentType").Parse(componentTemplate)) err = t.Execute(buffer, map[string]any{ "properties": propertiesString, "params": params, "constructorSetter": constructorSetter, "getSet": getSetString, "packet": packetName, "imports": strings.Join(c.imports, "\n"), "className": util.Title(defineStruct.Name()), "superClassName": superClassName, "HasProperty": len(strings.TrimSpace(propertiesString)) > 0, "version": version.BuildVersion, }) if err != nil { return err } _, err = fp.WriteString(formatSource(buffer.String())) return err } func (c *componentsContext) checkStruct(ty spec.Type) (spec.DefineStruct, bool, error) { defineStruct, ok := ty.(spec.DefineStruct) if !ok { return spec.DefineStruct{}, true, errors.New("unsupported type %s" + ty.Name()) } for _, item := range c.requestTypes { if item.Name() == defineStruct.Name() { if len(defineStruct.GetFormMembers())+len(defineStruct.GetBodyMembers()) == 0 { return spec.DefineStruct{}, true, nil } } } return defineStruct, false, nil } func (c *componentsContext) buildProperties(defineStruct spec.DefineStruct) (string, error) { var builder strings.Builder if err := c.writeType(&builder, defineStruct); err != nil { return "", apiutil.WrapErr(err, "Type "+defineStruct.Name()+" generate error") } return builder.String(), nil } func (c *componentsContext) buildGetterSetter(defineStruct spec.DefineStruct) (string, error) { var builder strings.Builder if err := c.genGetSet(&builder, 1); err != nil { return "", apiutil.WrapErr(err, "Type "+defineStruct.Name()+" get or set generate error") } return builder.String(), nil } func (c *componentsContext) writeType(writer io.Writer, defineStruct spec.DefineStruct) error { c.members = make([]spec.Member, 0) err := c.writeMembers(writer, defineStruct, 1) if err != nil { return err } return nil } func (c *componentsContext) writeMembers(writer io.Writer, tp spec.Type, indent int) error { definedType, ok := tp.(spec.DefineStruct) if !ok { pointType, ok := tp.(spec.PointerType) if ok { return c.writeMembers(writer, pointType.Type, indent) } return fmt.Errorf("type %s not supported", tp.Name()) } for _, member := range definedType.Members { if member.IsInline { err := c.writeMembers(writer, member.Type, indent) if err != nil { return err } continue } if member.IsBodyMember() || member.IsFormMember() { if err := writeProperty(writer, member, indent); err != nil { return err } c.members = append(c.members, member) } } return nil } func (c *componentsContext) buildConstructor() (string, string, error) { var params strings.Builder var constructorSetter strings.Builder for index, member := range c.members { tp, err := specTypeToJava(member.Type) if err != nil { return "", "", err } params.WriteString(fmt.Sprintf("%s %s", tp, util.Untitle(member.Name))) pn, err := member.GetPropertyName() if err != nil { return "", "", err } if index != len(c.members)-1 { params.WriteString(", ") } writeIndent(&constructorSetter, 2) constructorSetter.WriteString(fmt.Sprintf("this.%s = %s;", pn, util.Untitle(member.Name))) if index != len(c.members)-1 { constructorSetter.WriteString(pathx.NL) } } return params.String(), constructorSetter.String(), nil } func (c *componentsContext) genGetSet(writer io.Writer, indent int) error { members := c.members for _, member := range members { javaType, err := specTypeToJava(member.Type) if err != nil { return nil } property := util.Title(member.Name) templateStr := getSetTemplate if javaType == "boolean" { templateStr = boolTemplate property = strings.TrimPrefix(property, "Is") property = strings.TrimPrefix(property, "is") } t := template.Must(template.New(templateStr).Parse(getSetTemplate)) var tmplBytes bytes.Buffer tyString := javaType decorator := "" javaPrimitiveType := []string{"int", "long", "boolean", "float", "double", "short"} if !slices.Contains(javaPrimitiveType, javaType) { if member.IsOptional() || member.IsOmitEmpty() { decorator = "@Nullable " } else { decorator = "@NotNull " } tyString = decorator + tyString } tagName, err := member.GetPropertyName() if err != nil { return err } err = t.Execute(&tmplBytes, map[string]string{ "property": property, "propertyValue": util.Untitle(member.Name), "tagValue": tagName, "type": tyString, "decorator": decorator, "returnType": javaType, "indent": indentString(indent), }) if err != nil { return err } r := tmplBytes.String() r = strings.Replace(r, " boolean get", " boolean is", 1) writer.Write([]byte(r)) } return nil } func formatSource(source string) string { var builder strings.Builder scanner := bufio.NewScanner(strings.NewReader(source)) preIsBreakLine := false for scanner.Scan() { text := strings.TrimSpace(scanner.Text()) if text == "" && preIsBreakLine { continue } preIsBreakLine = text == "" builder.WriteString(scanner.Text() + "\n") } if err := scanner.Err(); err != nil { fmt.Println(err) } return builder.String() }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/javagen/vars.go
tools/goctl/api/javagen/vars.go
package javagen const modelDir = "model"
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/annotation_test.go
tools/goctl/api/swagger/annotation_test.go
package swagger import ( "testing" "github.com/stretchr/testify/assert" ) func Test_getBoolFromKVOrDefault(t *testing.T) { properties := map[string]string{ "enabled": `"true"`, "disabled": `"false"`, "invalid": `"notabool"`, "empty_value": `""`, } assert.True(t, getBoolFromKVOrDefault(properties, "enabled", false)) assert.False(t, getBoolFromKVOrDefault(properties, "disabled", true)) assert.False(t, getBoolFromKVOrDefault(properties, "invalid", false)) assert.True(t, getBoolFromKVOrDefault(properties, "missing", true)) assert.False(t, getBoolFromKVOrDefault(properties, "empty_value", false)) assert.False(t, getBoolFromKVOrDefault(nil, "nil", false)) assert.False(t, getBoolFromKVOrDefault(map[string]string{}, "empty", false)) // Test with unquoted values (as stored by RawText()) unquotedProperties := map[string]string{ "enabled": "true", "disabled": "false", "invalid": "notabool", "empty_value": "", } assert.True(t, getBoolFromKVOrDefault(unquotedProperties, "enabled", false)) assert.False(t, getBoolFromKVOrDefault(unquotedProperties, "disabled", true)) assert.False(t, getBoolFromKVOrDefault(unquotedProperties, "invalid", false)) assert.False(t, getBoolFromKVOrDefault(unquotedProperties, "empty_value", false)) } func Test_getStringFromKVOrDefault(t *testing.T) { properties := map[string]string{ "name": `"example"`, "empty": `""`, } assert.Equal(t, "example", getStringFromKVOrDefault(properties, "name", "default")) assert.Equal(t, "default", getStringFromKVOrDefault(properties, "empty", "default")) assert.Equal(t, "default", getStringFromKVOrDefault(properties, "missing", "default")) assert.Equal(t, "default", getStringFromKVOrDefault(nil, "nil", "default")) assert.Equal(t, "default", getStringFromKVOrDefault(map[string]string{}, "empty", "default")) // Test with unquoted values (as stored by RawText()) unquotedProperties := map[string]string{ "name": "example", "title": "Demo API", "empty": "", } assert.Equal(t, "example", getStringFromKVOrDefault(unquotedProperties, "name", "default")) assert.Equal(t, "Demo API", getStringFromKVOrDefault(unquotedProperties, "title", "default")) assert.Equal(t, "default", getStringFromKVOrDefault(unquotedProperties, "empty", "default")) } func Test_getListFromInfoOrDefault(t *testing.T) { properties := map[string]string{ "list": `"a, b, c"`, "empty": `""`, } assert.Equal(t, []string{"a", " b", " c"}, getListFromInfoOrDefault(properties, "list", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(properties, "empty", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(properties, "missing", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(nil, "nil", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(map[string]string{}, "empty", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(map[string]string{ "foo": ",,", }, "foo", []string{"default"})) // Test with unquoted values (as stored by RawText()) unquotedProperties := map[string]string{ "list": "a, b, c", "schemes": "http,https", "tags": "query", "empty": "", } // Note: FieldsAndTrimSpace doesn't actually trim the spaces from returned values assert.Equal(t, []string{"a", " b", " c"}, getListFromInfoOrDefault(unquotedProperties, "list", []string{"default"})) assert.Equal(t, []string{"http", "https"}, getListFromInfoOrDefault(unquotedProperties, "schemes", []string{"default"})) assert.Equal(t, []string{"query"}, getListFromInfoOrDefault(unquotedProperties, "tags", []string{"default"})) assert.Equal(t, []string{"default"}, getListFromInfoOrDefault(unquotedProperties, "empty", []string{"default"})) } func Test_getFirstUsableString(t *testing.T) { t.Run("empty input", func(t *testing.T) { result := getFirstUsableString() assert.Equal(t, "", result, "should return empty string for no arguments") }) t.Run("single plain string", func(t *testing.T) { result := getFirstUsableString("Check server health status.") assert.Equal(t, "Check server health status.", result) }) t.Run("single quoted string", func(t *testing.T) { // This is how Go would represent a quoted string literal result := getFirstUsableString(`"Check server health status."`) assert.Equal(t, "Check server health status.", result, "should unquote quoted strings") }) t.Run("multiple plain strings", func(t *testing.T) { result := getFirstUsableString("", "second", "third") assert.Equal(t, "second", result, "should return first non-empty string") }) t.Run("handler name fallback", func(t *testing.T) { // Simulates the real use case: @doc text, handler name result := getFirstUsableString("", "HealthCheck") assert.Equal(t, "HealthCheck", result, "should fallback to handler name") }) t.Run("doc text over handler name", func(t *testing.T) { // Simulates the real use case with @doc text result := getFirstUsableString("Check server health status.", "HealthCheck") assert.Equal(t, "Check server health status.", result, "should use doc text over handler name") }) t.Run("empty strings before valid", func(t *testing.T) { result := getFirstUsableString("", "", "valid") assert.Equal(t, "valid", result, "should skip empty strings") }) t.Run("all empty strings", func(t *testing.T) { result := getFirstUsableString("", "", "") assert.Equal(t, "", result, "should return empty if all are empty") }) t.Run("quoted then plain", func(t *testing.T) { result := getFirstUsableString(`"quoted"`, "plain") assert.Equal(t, "quoted", result, "should unquote first quoted string") }) t.Run("plain then quoted", func(t *testing.T) { result := getFirstUsableString("plain", `"quoted"`) assert.Equal(t, "plain", result, "should use first plain string") }) t.Run("invalid quoted string", func(t *testing.T) { // String that looks quoted but isn't valid Go syntax result := getFirstUsableString(`"incomplete`, "fallback") assert.Equal(t, `"incomplete`, result, "should use as-is if unquote fails but not empty") }) t.Run("whitespace only", func(t *testing.T) { result := getFirstUsableString(" ", "fallback") assert.Equal(t, " ", result, "should not trim whitespace, return as-is") }) t.Run("real world API doc scenario", func(t *testing.T) { // This is the actual bug scenario from issue #5229 atDocText := "Check server health status." handlerName := "HealthCheck" result := getFirstUsableString(atDocText, handlerName) assert.Equal(t, "Check server health status.", result, "should use @doc text for API summary") }) t.Run("real world with empty doc", func(t *testing.T) { // When @doc is empty, should fall back to handler name atDocText := "" handlerName := "HealthCheck" result := getFirstUsableString(atDocText, handlerName) assert.Equal(t, "HealthCheck", result, "should fallback to handler name when @doc is empty") }) t.Run("complex summary with special characters", func(t *testing.T) { result := getFirstUsableString("Get user by ID: /users/{id}") assert.Equal(t, "Get user by ID: /users/{id}", result, "should handle special characters in plain strings") }) t.Run("multiline string", func(t *testing.T) { result := getFirstUsableString("Line 1\nLine 2") assert.Equal(t, "Line 1\nLine 2", result, "should handle multiline strings") }) t.Run("unicode characters", func(t *testing.T) { result := getFirstUsableString("健康检查", "HealthCheck") assert.Equal(t, "健康检查", result, "should handle unicode characters") }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/api.go
tools/goctl/api/swagger/api.go
package swagger import "github.com/zeromicro/go-zero/tools/goctl/api/spec" func fillAllStructs(api *spec.ApiSpec) { var ( tps []spec.Type structTypes = make(map[string]spec.DefineStruct) groups []spec.Group ) for _, tp := range api.Types { structTypes[tp.Name()] = tp.(spec.DefineStruct) } for _, tp := range api.Types { filledTP := fillStruct("", tp, structTypes) tps = append(tps, filledTP) structTypes[filledTP.Name()] = filledTP.(spec.DefineStruct) } for _, group := range api.Service.Groups { routes := make([]spec.Route, 0, len(group.Routes)) for _, route := range group.Routes { route.RequestType = fillStruct("", route.RequestType, structTypes) route.ResponseType = fillStruct("", route.ResponseType, structTypes) routes = append(routes, route) } group.Routes = routes groups = append(groups, group) } api.Service.Groups = groups api.Types = tps } func fillStruct(parent string, tp spec.Type, allTypes map[string]spec.DefineStruct) spec.Type { switch val := tp.(type) { case spec.DefineStruct: var members []spec.Member for _, member := range val.Members { switch memberType := member.Type.(type) { case spec.PointerType: member.Type = spec.PointerType{ RawName: memberType.RawName, Type: fillStruct(val.Name(), memberType.Type, allTypes), } case spec.ArrayType: member.Type = spec.ArrayType{ RawName: memberType.RawName, Value: fillStruct(val.Name(), memberType.Value, allTypes), } case spec.MapType: member.Type = spec.MapType{ RawName: memberType.RawName, Key: memberType.Key, Value: fillStruct(val.Name(), memberType.Value, allTypes), } case spec.DefineStruct: if parent != memberType.Name() { // avoid recursive struct if st, ok := allTypes[memberType.Name()]; ok { member.Type = fillStruct("", st, allTypes) } } case spec.NestedStruct: member.Type = fillStruct("", member.Type, allTypes) } members = append(members, member) } if len(members) == 0 { st, ok := allTypes[val.RawName] if ok { members = st.Members } } val.Members = members return val case spec.NestedStruct: members := make([]spec.Member, 0, len(val.Members)) for _, member := range val.Members { switch memberType := member.Type.(type) { case spec.PointerType: member.Type = spec.PointerType{ RawName: memberType.RawName, Type: fillStruct(val.Name(), memberType.Type, allTypes), } case spec.ArrayType: member.Type = spec.ArrayType{ RawName: memberType.RawName, Value: fillStruct(val.Name(), memberType.Value, allTypes), } case spec.MapType: member.Type = spec.MapType{ RawName: memberType.RawName, Key: memberType.Key, Value: fillStruct(val.Name(), memberType.Value, allTypes), } case spec.DefineStruct: if parent != memberType.Name() { // avoid recursive struct if st, ok := allTypes[memberType.Name()]; ok { member.Type = fillStruct("", st, allTypes) } } case spec.NestedStruct: if parent != memberType.Name() { if st, ok := allTypes[memberType.Name()]; ok { member.Type = fillStruct("", st, allTypes) } } } members = append(members, member) } if len(members) == 0 { st, ok := allTypes[val.RawName] if ok { members = st.Members } } val.Members = members return val case spec.PointerType: return spec.PointerType{ RawName: val.RawName, Type: fillStruct(parent, val.Type, allTypes), } case spec.ArrayType: return spec.ArrayType{ RawName: val.RawName, Value: fillStruct(parent, val.Value, allTypes), } case spec.MapType: return spec.MapType{ RawName: val.RawName, Key: val.Key, Value: fillStruct(parent, val.Value, allTypes), } default: return tp } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/contenttype.go
tools/goctl/api/swagger/contenttype.go
package swagger import ( "net/http" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func consumesFromTypeOrDef(ctx Context, method string, tp spec.Type) []string { if strings.EqualFold(method, http.MethodGet) { return []string{} } if tp == nil { return []string{} } structType, ok := tp.(spec.DefineStruct) if !ok { return []string{} } if typeContainsTag(ctx, structType, tagJson) { return []string{applicationJson} } return []string{applicationForm} }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/path.go
tools/goctl/api/swagger/path.go
package swagger import ( "net/http" "path" "strings" "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/util/stringx" ) func spec2Paths(ctx Context, srv apiSpec.Service) *spec.Paths { paths := &spec.Paths{ Paths: make(map[string]spec.PathItem), } for _, group := range srv.Groups { prefix := path.Clean(strings.TrimPrefix(group.GetAnnotation(propertyKeyPrefix), "/")) for _, route := range group.Routes { routPath := pathVariable2SwaggerVariable(ctx, route.Path) if len(prefix) > 0 && prefix != "." { if routPath == "/" { routPath = "/" + path.Clean(prefix) } else { routPath = "/" + path.Clean(prefix) + routPath } } pathItem := spec2Path(ctx, group, route) existPathItem, ok := paths.Paths[routPath] if !ok { paths.Paths[routPath] = pathItem } else { paths.Paths[routPath] = mergePathItem(existPathItem, pathItem) } } } return paths } func mergePathItem(old, new spec.PathItem) spec.PathItem { if new.Get != nil { old.Get = new.Get } if new.Put != nil { old.Put = new.Put } if new.Post != nil { old.Post = new.Post } if new.Delete != nil { old.Delete = new.Delete } if new.Options != nil { old.Options = new.Options } if new.Head != nil { old.Head = new.Head } if new.Patch != nil { old.Patch = new.Patch } if new.Parameters != nil { old.Parameters = new.Parameters } return old } func spec2Path(ctx Context, group apiSpec.Group, route apiSpec.Route) spec.PathItem { authType := getStringFromKVOrDefault(group.Annotation.Properties, propertyKeyAuthType, "") var security []map[string][]string if len(authType) > 0 { security = []map[string][]string{ { authType: []string{}, }, } } groupName := getStringFromKVOrDefault(group.Annotation.Properties, propertyKeyGroup, "") operationId := route.Handler if len(groupName) > 0 { operationId = stringx.From(groupName + "_" + route.Handler).ToCamel() } operationId = stringx.From(operationId).Untitle() op := &spec.Operation{ OperationProps: spec.OperationProps{ Description: getStringFromKVOrDefault(route.AtDoc.Properties, propertyKeyDescription, ""), Consumes: consumesFromTypeOrDef(ctx, route.Method, route.RequestType), Produces: getListFromInfoOrDefault(route.AtDoc.Properties, propertyKeyProduces, []string{applicationJson}), Schemes: getListFromInfoOrDefault(route.AtDoc.Properties, propertyKeySchemes, []string{schemeHttps}), Tags: getListFromInfoOrDefault(group.Annotation.Properties, propertyKeyTags, getListFromInfoOrDefault(group.Annotation.Properties, propertyKeySummary, []string{})), Summary: getStringFromKVOrDefault(route.AtDoc.Properties, propertyKeySummary, getFirstUsableString(route.AtDoc.Text, route.Handler)), ID: operationId, Deprecated: getBoolFromKVOrDefault(route.AtDoc.Properties, propertyKeyDeprecated, false), Parameters: parametersFromType(ctx, route.Method, route.RequestType), Security: security, Responses: jsonResponseFromType(ctx, route.AtDoc, route.ResponseType), }, } externalDocsDescription := getStringFromKVOrDefault(route.AtDoc.Properties, propertyKeyExternalDocsDescription, "") externalDocsURL := getStringFromKVOrDefault(route.AtDoc.Properties, propertyKeyExternalDocsURL, "") if len(externalDocsDescription) > 0 || len(externalDocsURL) > 0 { op.ExternalDocs = &spec.ExternalDocumentation{ Description: externalDocsDescription, URL: externalDocsURL, } } item := spec.PathItem{} switch strings.ToUpper(route.Method) { case http.MethodGet: item.Get = op case http.MethodHead: item.Head = op case http.MethodPost: item.Post = op case http.MethodPut: item.Put = op case http.MethodPatch: item.Patch = op case http.MethodDelete: item.Delete = op case http.MethodOptions: item.Options = op default: // [http.MethodConnect,http.MethodTrace] not supported } return item }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/contenttype_test.go
tools/goctl/api/swagger/contenttype_test.go
package swagger import ( "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func TestConsumesFromTypeOrDef(t *testing.T) { tests := []struct { name string method string tp spec.Type expected []string }{ { name: "GET method with nil type", method: http.MethodGet, tp: nil, expected: []string{}, }, { name: "post nil", method: http.MethodPost, tp: nil, expected: []string{}, }, { name: "json tag", method: http.MethodPost, tp: spec.DefineStruct{ Members: []spec.Member{ { Tag: `json:"example"`, }, }, }, expected: []string{applicationJson}, }, { name: "form tag", method: http.MethodPost, tp: spec.DefineStruct{ Members: []spec.Member{ { Tag: `form:"example"`, }, }, }, expected: []string{applicationForm}, }, { name: "Non struct type", method: http.MethodPost, tp: spec.ArrayType{}, expected: []string{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := consumesFromTypeOrDef(testingContext(t), tt.method, tt.tp) assert.Equal(t, tt.expected, result) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/response.go
tools/goctl/api/swagger/response.go
package swagger import ( "net/http" "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func jsonResponseFromType(ctx Context, atDoc apiSpec.AtDoc, tp apiSpec.Type) *spec.Responses { if tp == nil { return &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: map[int]spec.Response{ http.StatusOK: { ResponseProps: spec.ResponseProps{ Description: "", Schema: &spec.Schema{}, }, }, }, }, } } props := spec.SchemaProps{ AdditionalProperties: mapFromGoType(ctx, tp), Items: itemsFromGoType(ctx, tp), } if ctx.UseDefinitions { structName, ok := containsStruct(tp) if ok { props.Ref = spec.MustCreateRef(getRefName(structName)) return &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: map[int]spec.Response{ http.StatusOK: { ResponseProps: spec.ResponseProps{ Schema: &spec.Schema{ SchemaProps: wrapCodeMsgProps(ctx, props, atDoc), }, }, }, }, }, } } } p, _ := propertiesFromType(ctx, tp) props.Type = typeFromGoType(ctx, tp) props.Properties = p return &spec.Responses{ ResponsesProps: spec.ResponsesProps{ StatusCodeResponses: map[int]spec.Response{ http.StatusOK: { ResponseProps: spec.ResponseProps{ Schema: &spec.Schema{ SchemaProps: wrapCodeMsgProps(ctx, props, atDoc), }, }, }, }, }, } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/path_test.go
tools/goctl/api/swagger/path_test.go
package swagger import ( "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func TestSpec2PathsWithRootRoute(t *testing.T) { tests := []struct { name string prefix string routePath string expectedPath string }{ { name: "prefix with root route", prefix: "/api/v1/shoppings", routePath: "/", expectedPath: "/api/v1/shoppings", }, { name: "prefix with sub route", prefix: "/api/v1/shoppings", routePath: "/list", expectedPath: "/api/v1/shoppings/list", }, { name: "empty prefix with root route", prefix: "", routePath: "/", expectedPath: "/", }, { name: "empty prefix with sub route", prefix: "", routePath: "/list", expectedPath: "/list", }, { name: "prefix with trailing slash and root route", prefix: "/api/v1/shoppings/", routePath: "/", expectedPath: "/api/v1/shoppings", }, { name: "prefix without leading slash and root route", prefix: "api/v1/shoppings", routePath: "/", expectedPath: "/api/v1/shoppings", }, { name: "single level prefix with root route", prefix: "/api", routePath: "/", expectedPath: "/api", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { srv := spec.Service{ Groups: []spec.Group{ { Annotation: spec.Annotation{ Properties: map[string]string{ propertyKeyPrefix: tt.prefix, }, }, Routes: []spec.Route{ { Method: "get", Path: tt.routePath, Handler: "TestHandler", }, }, }, }, } ctx := testingContext(t) paths := spec2Paths(ctx, srv) assert.Contains(t, paths.Paths, tt.expectedPath, "Expected path %s not found in generated paths. Got: %v", tt.expectedPath, paths.Paths) }) } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/parameter_test.go
tools/goctl/api/swagger/parameter_test.go
package swagger import ( "net/http" "testing" "github.com/stretchr/testify/assert" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func TestIsRequestBodyJson(t *testing.T) { tests := []struct { name string method string hasJson bool expected bool }{ {"POST with JSON", http.MethodPost, true, true}, {"POST without JSON", http.MethodPost, false, false}, {"GET with JSON", http.MethodGet, true, false}, {"PUT with JSON", http.MethodPut, true, true}, {"PUT without JSON", http.MethodPut, false, false}, {"PATCH with JSON", http.MethodPatch, true, true}, {"PATCH without JSON", http.MethodPatch, false, false}, {"DELETE with JSON", http.MethodDelete, true, true}, {"DELETE without JSON", http.MethodDelete, false, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { testStruct := createTestStruct("TestStruct", tt.hasJson) _, result := isRequestBodyJson(testingContext(t), tt.method, testStruct) assert.Equal(t, tt.expected, result) }) } } func TestParametersFromType(t *testing.T) { tests := []struct { name string method string useDefinitions bool hasJson bool expectedCount int expectedBody bool }{ {"POST JSON with definitions", http.MethodPost, true, true, 1, true}, {"POST JSON without definitions", http.MethodPost, false, true, 1, true}, {"PUT JSON with definitions", http.MethodPut, true, true, 1, true}, {"PUT JSON without definitions", http.MethodPut, false, true, 1, true}, {"PATCH JSON with definitions", http.MethodPatch, true, true, 1, true}, {"PATCH JSON without definitions", http.MethodPatch, false, true, 1, true}, {"DELETE JSON with definitions", http.MethodDelete, true, true, 1, true}, {"DELETE JSON without definitions", http.MethodDelete, false, true, 1, true}, {"GET with form", http.MethodGet, false, false, 1, false}, {"POST with form", http.MethodPost, false, false, 1, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { ctx := Context{UseDefinitions: tt.useDefinitions} testStruct := createTestStruct("TestStruct", tt.hasJson) params := parametersFromType(ctx, tt.method, testStruct) assert.Equal(t, tt.expectedCount, len(params)) if tt.expectedBody { assert.Equal(t, paramsInBody, params[0].In) } else if len(params) > 0 { assert.NotEqual(t, paramsInBody, params[0].In) } }) } } func TestParametersFromType_EdgeCases(t *testing.T) { ctx := testingContext(t) params := parametersFromType(ctx, http.MethodPost, nil) assert.Empty(t, params) primitiveType := apiSpec.PrimitiveType{RawName: "string"} params = parametersFromType(ctx, http.MethodPost, primitiveType) assert.Empty(t, params) } func createTestStruct(name string, hasJson bool) apiSpec.DefineStruct { tag := `form:"username"` if hasJson { tag = `json:"username"` } return apiSpec.DefineStruct{ RawName: name, Members: []apiSpec.Member{ { Name: "Username", Type: apiSpec.PrimitiveType{RawName: "string"}, Tag: tag, }, }, } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/swagger_test.go
tools/goctl/api/swagger/swagger_test.go
package swagger import ( "testing" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/stretchr/testify/assert" ) func Test_pathVariable2SwaggerVariable(t *testing.T) { testCases := []struct { input string expected string }{ {input: "/api/:id", expected: "/api/{id}"}, {input: "/api/:id/details", expected: "/api/{id}/details"}, {input: "/:version/api/:id", expected: "/{version}/api/{id}"}, {input: "/api/v1", expected: "/api/v1"}, {input: "/api/:id/:action", expected: "/api/{id}/{action}"}, } for _, tc := range testCases { result := pathVariable2SwaggerVariable(testingContext(t), tc.input) assert.Equal(t, tc.expected, result) } } func TestArrayDefinitionsBug(t *testing.T) { // Test case for the bug where array of structs with useDefinitions // generates incorrect swagger JSON structure // Context with useDefinitions enabled ctx := Context{ UseDefinitions: true, } // Create a test struct containing an array of structs testStruct := spec.DefineStruct{ RawName: "TestStruct", Members: []spec.Member{ { Name: "ArrayField", Type: spec.ArrayType{ Value: spec.DefineStruct{ RawName: "ItemStruct", Members: []spec.Member{ { Name: "ItemName", Type: spec.PrimitiveType{RawName: "string"}, Tag: `json:"itemName"`, }, }, }, }, Tag: `json:"arrayField"`, }, }, } // Get properties from the struct properties, _ := propertiesFromType(ctx, testStruct) // Check that we have the array field assert.Contains(t, properties, "arrayField") arrayField := properties["arrayField"] // Verify the array field has correct structure assert.Equal(t, "array", arrayField.Type[0]) // Check that we have items assert.NotNil(t, arrayField.Items, "Array should have items defined") assert.NotNil(t, arrayField.Items.Schema, "Array items should have schema") // The FIX: $ref should be inside items, not at schema level hasRef := arrayField.Ref.String() != "" assert.False(t, hasRef, "Schema level should NOT have $ref") // The $ref should be in the items hasItemsRef := arrayField.Items.Schema.Ref.String() != "" assert.True(t, hasItemsRef, "Items should have $ref") assert.Equal(t, "#/definitions/ItemStruct", arrayField.Items.Schema.Ref.String()) // Verify there are no other properties in the items when using $ref assert.Nil(t, arrayField.Items.Schema.Properties, "Items with $ref should not have properties") assert.Empty(t, arrayField.Items.Schema.Required, "Items with $ref should not have required") assert.Empty(t, arrayField.Items.Schema.Type, "Items with $ref should not have type") } func TestArrayWithoutDefinitions(t *testing.T) { // Test that arrays work correctly when useDefinitions is false ctx := Context{ UseDefinitions: false, // This is the default } // Create the same test struct testStruct := spec.DefineStruct{ RawName: "TestStruct", Members: []spec.Member{ { Name: "ArrayField", Type: spec.ArrayType{ Value: spec.DefineStruct{ RawName: "ItemStruct", Members: []spec.Member{ { Name: "ItemName", Type: spec.PrimitiveType{RawName: "string"}, Tag: `json:"itemName"`, }, }, }, }, Tag: `json:"arrayField"`, }, }, } properties, _ := propertiesFromType(ctx, testStruct) assert.Contains(t, properties, "arrayField") arrayField := properties["arrayField"] // Should be array type assert.Equal(t, "array", arrayField.Type[0]) // Should have items with full schema, no $ref assert.NotNil(t, arrayField.Items) assert.NotNil(t, arrayField.Items.Schema) // Should NOT have $ref at schema level assert.Empty(t, arrayField.Ref.String(), "Schema should not have $ref when useDefinitions is false") // Should NOT have $ref in items either assert.Empty(t, arrayField.Items.Schema.Ref.String(), "Items should not have $ref when useDefinitions is false") // Should have full schema properties in items assert.Equal(t, "object", arrayField.Items.Schema.Type[0]) assert.Contains(t, arrayField.Items.Schema.Properties, "itemName") assert.Equal(t, []string{"itemName"}, arrayField.Items.Schema.Required) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/const.go
tools/goctl/api/swagger/const.go
package swagger const ( tagHeader = "header" tagPath = "path" tagForm = "form" tagJson = "json" defFlag = "default=" enumFlag = "options=" rangeFlag = "range=" exampleFlag = "example=" optionalFlag = "optional" paramsInHeader = "header" paramsInPath = "path" paramsInQuery = "query" paramsInBody = "body" paramsInForm = "formData" swaggerTypeInteger = "integer" swaggerTypeNumber = "number" swaggerTypeString = "string" swaggerTypeBoolean = "boolean" swaggerTypeArray = "array" swaggerTypeObject = "object" swaggerVersion = "2.0" applicationJson = "application/json" applicationForm = "application/x-www-form-urlencoded" schemeHttps = "https" defaultBasePath = "/" ) const ( propertyKeyUseDefinitions = "useDefinitions" propertyKeyExternalDocsDescription = "externalDocsDescription" propertyKeyExternalDocsURL = "externalDocsURL" propertyKeyTitle = "title" propertyKeyTermsOfService = "termsOfService" propertyKeyDescription = "description" propertyKeyVersion = "version" propertyKeyContactName = "contactName" propertyKeyContactURL = "contactURL" propertyKeyContactEmail = "contactEmail" propertyKeyLicenseName = "licenseName" propertyKeyLicenseURL = "licenseURL" propertyKeyProduces = "produces" propertyKeyConsumes = "consumes" propertyKeySchemes = "schemes" propertyKeyTags = "tags" propertyKeySummary = "summary" propertyKeyGroup = "group" propertyKeyOperationId = "operationId" propertyKeyDeprecated = "deprecated" propertyKeyPrefix = "prefix" propertyKeyAuthType = "authType" propertyKeyHost = "host" propertyKeyBasePath = "basePath" propertyKeyWrapCodeMsg = "wrapCodeMsg" propertyKeyBizCodeEnumDescription = "bizCodeEnumDescription" ) const ( defaultValueOfPropertyUseDefinition = false )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/properties.go
tools/goctl/api/swagger/properties.go
package swagger import ( "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func propertiesFromType(ctx Context, tp apiSpec.Type) (spec.SchemaProperties, []string) { var ( properties = map[string]spec.Schema{} requiredFields []string ) switch val := tp.(type) { case apiSpec.PointerType: return propertiesFromType(ctx, val.Type) case apiSpec.ArrayType: return propertiesFromType(ctx, val.Value) case apiSpec.DefineStruct, apiSpec.NestedStruct: rangeMemberAndDo(ctx, val, func(tag *apiSpec.Tags, required bool, member apiSpec.Member) { var ( jsonTagString = member.Name minimum, maximum *float64 exclusiveMinimum, exclusiveMaximum bool example, defaultValue any enum []any ) pathTag, _ := tag.Get(tagPath) if pathTag != nil { return } formTag, _ := tag.Get(tagForm) if formTag != nil { return } headerTag, _ := tag.Get(tagHeader) if headerTag != nil { return } jsonTag, _ := tag.Get(tagJson) if jsonTag != nil { jsonTagString = jsonTag.Name minimum, maximum, exclusiveMinimum, exclusiveMaximum = rangeValueFromOptions(jsonTag.Options) example = exampleValueFromOptions(ctx, jsonTag.Options, member.Type) defaultValue = defValueFromOptions(ctx, jsonTag.Options, member.Type) enum = enumsValueFromOptions(jsonTag.Options) } if required { requiredFields = append(requiredFields, jsonTagString) } schema := spec.Schema{ SwaggerSchemaProps: spec.SwaggerSchemaProps{ Example: example, }, SchemaProps: spec.SchemaProps{ Description: formatComment(member.Comment), Type: typeFromGoType(ctx, member.Type), Default: defaultValue, Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enum, AdditionalProperties: mapFromGoType(ctx, member.Type), }, } switch sampleTypeFromGoType(ctx, member.Type) { case swaggerTypeArray: schema.Items = itemsFromGoType(ctx, member.Type) // Special handling for arrays with useDefinitions if ctx.UseDefinitions { // For arrays, check if the array element (not the array itself) contains a struct if arrayType, ok := member.Type.(apiSpec.ArrayType); ok { if structName, containsStruct := containsStruct(arrayType.Value); containsStruct { // Set the $ref inside the items, not at the schema level schema.Items = &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Ref: spec.MustCreateRef(getRefName(structName)), }, }, } } } } case swaggerTypeObject: p, r := propertiesFromType(ctx, member.Type) schema.Properties = p schema.Required = r // For objects with useDefinitions, set $ref at schema level if ctx.UseDefinitions { structName, containsStruct := containsStruct(member.Type) if containsStruct { schema.SchemaProps.Ref = spec.MustCreateRef(getRefName(structName)) } } default: // For non-array, non-object types, apply useDefinitions logic if ctx.UseDefinitions { structName, containsStruct := containsStruct(member.Type) if containsStruct { schema.SchemaProps.Ref = spec.MustCreateRef(getRefName(structName)) } } } properties[jsonTagString] = schema }) } return properties, requiredFields } func containsStruct(tp apiSpec.Type) (string, bool) { switch val := tp.(type) { case apiSpec.PointerType: return containsStruct(val.Type) case apiSpec.ArrayType: return containsStruct(val.Value) case apiSpec.DefineStruct: return val.RawName, true case apiSpec.MapType: return containsStruct(val.Value) default: return "", false } } func getRefName(typeName string) string { return "#/definitions/" + typeName }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/options_test.go
tools/goctl/api/swagger/options_test.go
package swagger import ( "testing" "github.com/stretchr/testify/assert" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func TestRangeValueFromOptions(t *testing.T) { tests := []struct { name string options []string expectedMin *float64 expectedMax *float64 expectedExclMin bool expectedExclMax bool }{ { name: "Valid range with inclusive bounds", options: []string{"range=[1.0:10.0]"}, expectedMin: floatPtr(1.0), expectedMax: floatPtr(10.0), expectedExclMin: false, expectedExclMax: false, }, { name: "Valid range with exclusive bounds", options: []string{"range=(1.0:10.0)"}, expectedMin: floatPtr(1.0), expectedMax: floatPtr(10.0), expectedExclMin: true, expectedExclMax: true, }, { name: "Invalid range format", options: []string{"range=1.0:10.0"}, expectedMin: nil, expectedMax: nil, expectedExclMin: false, expectedExclMax: false, }, { name: "Invalid range start", options: []string{"range=[a:1.0)"}, expectedMin: nil, expectedMax: nil, expectedExclMin: false, expectedExclMax: false, }, { name: "Missing range end", options: []string{"range=[1.0:)"}, expectedMin: floatPtr(1.0), expectedMax: nil, expectedExclMin: false, expectedExclMax: true, }, { name: "Missing range start and end", options: []string{"range=[:)"}, expectedMin: nil, expectedMax: nil, expectedExclMin: false, expectedExclMax: true, }, { name: "Missing range start", options: []string{"range=[:1.0)"}, expectedMin: nil, expectedMax: floatPtr(1.0), expectedExclMin: false, expectedExclMax: true, }, { name: "Invalid range end", options: []string{"range=[1.0:b)"}, expectedMin: nil, expectedMax: nil, expectedExclMin: false, expectedExclMax: false, }, { name: "Empty options", options: []string{}, expectedMin: nil, expectedMax: nil, expectedExclMin: false, expectedExclMax: false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { min, max, exclMin, exclMax := rangeValueFromOptions(tt.options) assert.Equal(t, tt.expectedMin, min) assert.Equal(t, tt.expectedMax, max) assert.Equal(t, tt.expectedExclMin, exclMin) assert.Equal(t, tt.expectedExclMax, exclMax) }) } } func TestEnumsValueFromOptions(t *testing.T) { tests := []struct { name string options []string expected []any }{ { name: "Valid enums", options: []string{"options=a|b|c"}, expected: []any{"a", "b", "c"}, }, { name: "Empty enums", options: []string{"options="}, expected: []any{}, }, { name: "No enum option", options: []string{}, expected: []any{}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := enumsValueFromOptions(tt.options) assert.Equal(t, tt.expected, result) }) } } func TestDefValueFromOptions(t *testing.T) { tests := []struct { name string options []string apiType spec.Type expected any }{ { name: "Default integer value", options: []string{"default=42"}, apiType: spec.PrimitiveType{RawName: "int"}, expected: int64(42), }, { name: "Default string value", options: []string{"default=hello"}, apiType: spec.PrimitiveType{RawName: "string"}, expected: "hello", }, { name: "No default value", options: []string{}, apiType: spec.PrimitiveType{RawName: "string"}, expected: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := defValueFromOptions(testingContext(t), tt.options, tt.apiType) assert.Equal(t, tt.expected, result) }) } } func TestExampleValueFromOptions(t *testing.T) { tests := []struct { name string options []string apiType spec.Type expected any }{ { name: "Example value present", options: []string{"example=3.14"}, apiType: spec.PrimitiveType{RawName: "float"}, expected: 3.14, }, { name: "Fallback to default value", options: []string{"default=42"}, apiType: spec.PrimitiveType{RawName: "int"}, expected: int64(42), }, { name: "Fallback to default value", options: []string{"default="}, apiType: spec.PrimitiveType{RawName: "int"}, expected: int64(0), }, { name: "No example or default value", options: []string{}, apiType: spec.PrimitiveType{RawName: "string"}, expected: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { exampleValueFromOptions(testingContext(t), tt.options, tt.apiType) }) } } func TestValueFromOptions(t *testing.T) { tests := []struct { name string options []string key string tp string expected any }{ { name: "Integer value", options: []string{"default=42"}, key: "default=", tp: "integer", expected: int64(42), }, { name: "Boolean value", options: []string{"default=true"}, key: "default=", tp: "boolean", expected: true, }, { name: "Number value", options: []string{"default=1.1"}, key: "default=", tp: "number", expected: 1.1, }, { name: "No matching key", options: []string{"example=42"}, key: "default=", tp: "integer", expected: nil, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { result := valueFromOptions(testingContext(t), tt.options, tt.key, tt.tp) assert.Equal(t, tt.expected, result) }) } } func floatPtr(f float64) *float64 { return &f }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/swagger.go
tools/goctl/api/swagger/swagger.go
package swagger import ( "encoding/json" "strings" "time" "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/internal/version" ) func spec2Swagger(api *apiSpec.ApiSpec) (*spec.Swagger, error) { ctx := contextFromApi(api.Info) extensions, info := specExtensions(api.Info) var securityDefinitions spec.SecurityDefinitions securityDefinitionsFromJson := getStringFromKVOrDefault(api.Info.Properties, "securityDefinitionsFromJson", `{}`) _ = json.Unmarshal([]byte(securityDefinitionsFromJson), &securityDefinitions) swagger := &spec.Swagger{ VendorExtensible: spec.VendorExtensible{ Extensions: extensions, }, SwaggerProps: spec.SwaggerProps{ Definitions: definitionsFromTypes(ctx, api.Types), Consumes: getListFromInfoOrDefault(api.Info.Properties, propertyKeyConsumes, []string{applicationJson}), Produces: getListFromInfoOrDefault(api.Info.Properties, propertyKeyProduces, []string{applicationJson}), Schemes: getListFromInfoOrDefault(api.Info.Properties, propertyKeySchemes, []string{schemeHttps}), Swagger: swaggerVersion, Info: info, Host: getStringFromKVOrDefault(api.Info.Properties, propertyKeyHost, ""), BasePath: getStringFromKVOrDefault(api.Info.Properties, propertyKeyBasePath, defaultBasePath), Paths: spec2Paths(ctx, api.Service), SecurityDefinitions: securityDefinitions, }, } return swagger, nil } func formatComment(comment string) string { s := strings.TrimPrefix(comment, "//") return strings.TrimSpace(s) } func sampleItemsFromGoType(ctx Context, tp apiSpec.Type) *spec.Items { val, ok := tp.(apiSpec.ArrayType) if !ok { return nil } item := val.Value switch item.(type) { case apiSpec.PrimitiveType: return &spec.Items{ SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, item), }, } case apiSpec.ArrayType: return &spec.Items{ SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, item), Items: sampleItemsFromGoType(ctx, item), }, } default: // unsupported type } return nil } // itemsFromGoType returns the schema or array of the type, just for non json body parameters. func itemsFromGoType(ctx Context, tp apiSpec.Type) *spec.SchemaOrArray { array, ok := tp.(apiSpec.ArrayType) if !ok { return nil } return itemFromGoType(ctx, array.Value) } func mapFromGoType(ctx Context, tp apiSpec.Type) *spec.SchemaOrBool { mapType, ok := tp.(apiSpec.MapType) if !ok { return nil } var schema = &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: typeFromGoType(ctx, mapType.Value), AdditionalProperties: mapFromGoType(ctx, mapType.Value), }, } switch sampleTypeFromGoType(ctx, mapType.Value) { case swaggerTypeArray: schema.Items = itemsFromGoType(ctx, mapType.Value) case swaggerTypeObject: p, r := propertiesFromType(ctx, mapType.Value) schema.Properties = p schema.Required = r } return &spec.SchemaOrBool{ Allows: true, Schema: schema, } } // itemFromGoType returns the schema or array of the type, just for non json body parameters. func itemFromGoType(ctx Context, tp apiSpec.Type) *spec.SchemaOrArray { switch itemType := tp.(type) { case apiSpec.PrimitiveType: return &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: typeFromGoType(ctx, tp), }, }, } case apiSpec.DefineStruct, apiSpec.NestedStruct, apiSpec.MapType: properties, requiredFields := propertiesFromType(ctx, itemType) return &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: typeFromGoType(ctx, itemType), Items: itemsFromGoType(ctx, itemType), Properties: properties, Required: requiredFields, AdditionalProperties: mapFromGoType(ctx, itemType), }, }, } case apiSpec.PointerType: return itemFromGoType(ctx, itemType.Type) case apiSpec.ArrayType: return &spec.SchemaOrArray{ Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: typeFromGoType(ctx, itemType), Items: itemsFromGoType(ctx, itemType), }, }, } } return nil } func typeFromGoType(ctx Context, tp apiSpec.Type) []string { switch val := tp.(type) { case apiSpec.PrimitiveType: res, ok := tpMapper[val.RawName] if ok { return []string{res} } case apiSpec.ArrayType: return []string{swaggerTypeArray} case apiSpec.DefineStruct, apiSpec.MapType: return []string{swaggerTypeObject} case apiSpec.PointerType: return typeFromGoType(ctx, val.Type) } return nil } func sampleTypeFromGoType(ctx Context, tp apiSpec.Type) string { switch val := tp.(type) { case apiSpec.PrimitiveType: return tpMapper[val.RawName] case apiSpec.ArrayType: return swaggerTypeArray case apiSpec.DefineStruct, apiSpec.MapType, apiSpec.NestedStruct: return swaggerTypeObject case apiSpec.PointerType: return sampleTypeFromGoType(ctx, val.Type) default: return "" } } func typeContainsTag(ctx Context, structType apiSpec.DefineStruct, tag string) bool { members := expandMembers(ctx, structType) for _, member := range members { tags, _ := apiSpec.Parse(member.Tag) if _, err := tags.Get(tag); err == nil { return true } } return false } func expandMembers(ctx Context, tp apiSpec.Type) []apiSpec.Member { var members []apiSpec.Member switch val := tp.(type) { case apiSpec.DefineStruct: for _, v := range val.Members { if v.IsInline { members = append(members, expandMembers(ctx, v.Type)...) continue } members = append(members, v) } case apiSpec.NestedStruct: for _, v := range val.Members { if v.IsInline { members = append(members, expandMembers(ctx, v.Type)...) continue } members = append(members, v) } } return members } func rangeMemberAndDo(ctx Context, structType apiSpec.Type, do func(tag *apiSpec.Tags, required bool, member apiSpec.Member)) { var members = expandMembers(ctx, structType) for _, field := range members { tags, _ := apiSpec.Parse(field.Tag) required := isRequired(ctx, tags) do(tags, required, field) } } func isRequired(ctx Context, tags *apiSpec.Tags) bool { tag, err := tags.Get(tagJson) if err == nil { return !isOptional(ctx, tag.Options) } tag, err = tags.Get(tagForm) if err == nil { return !isOptional(ctx, tag.Options) } tag, err = tags.Get(tagPath) if err == nil { return !isOptional(ctx, tag.Options) } return false } func isOptional(_ Context, options []string) bool { for _, option := range options { if option == optionalFlag { return true } } return false } func pathVariable2SwaggerVariable(_ Context, path string) string { pathItems := strings.FieldsFunc(path, slashRune) resp := make([]string, 0, len(pathItems)) for _, v := range pathItems { if strings.HasPrefix(v, ":") { resp = append(resp, "{"+v[1:]+"}") } else { resp = append(resp, v) } } return "/" + strings.Join(resp, "/") } func wrapCodeMsgProps(ctx Context, properties spec.SchemaProps, atDoc apiSpec.AtDoc) spec.SchemaProps { if !ctx.WrapCodeMsg { return properties } globalCodeDesc := ctx.BizCodeEnumDescription methodCodeDesc := getStringFromKVOrDefault(atDoc.Properties, propertyKeyBizCodeEnumDescription, globalCodeDesc) return spec.SchemaProps{ Type: []string{swaggerTypeObject}, Properties: spec.SchemaProperties{ "code": { SwaggerSchemaProps: spec.SwaggerSchemaProps{ Example: 0, }, SchemaProps: spec.SchemaProps{ Type: []string{swaggerTypeInteger}, Description: methodCodeDesc, }, }, "msg": { SwaggerSchemaProps: spec.SwaggerSchemaProps{ Example: "ok", }, SchemaProps: spec.SchemaProps{ Type: []string{swaggerTypeString}, Description: "business message", }, }, "data": { SchemaProps: properties, }, }, } } func specExtensions(api apiSpec.Info) (spec.Extensions, *spec.Info) { ext := spec.Extensions{} ext.Add("x-goctl-version", version.BuildVersion) ext.Add("x-description", "This is a goctl generated swagger file.") ext.Add("x-date", time.Now().Format(time.DateTime)) ext.Add("x-github", "https://github.com/zeromicro/go-zero") ext.Add("x-go-zero-doc", "https://go-zero.dev/") info := &spec.Info{} info.Title = getStringFromKVOrDefault(api.Properties, propertyKeyTitle, "") info.Description = getStringFromKVOrDefault(api.Properties, propertyKeyDescription, "") info.TermsOfService = getStringFromKVOrDefault(api.Properties, propertyKeyTermsOfService, "") info.Version = getStringFromKVOrDefault(api.Properties, propertyKeyVersion, "1.0") contactInfo := spec.ContactInfo{} contactInfo.Name = getStringFromKVOrDefault(api.Properties, propertyKeyContactName, "") contactInfo.URL = getStringFromKVOrDefault(api.Properties, propertyKeyContactURL, "") contactInfo.Email = getStringFromKVOrDefault(api.Properties, propertyKeyContactEmail, "") if len(contactInfo.Name) > 0 || len(contactInfo.URL) > 0 || len(contactInfo.Email) > 0 { info.Contact = &contactInfo } license := &spec.License{} license.Name = getStringFromKVOrDefault(api.Properties, propertyKeyLicenseName, "") license.URL = getStringFromKVOrDefault(api.Properties, propertyKeyLicenseURL, "") if len(license.Name) > 0 || len(license.URL) > 0 { info.License = license } return ext, info }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/options.go
tools/goctl/api/swagger/options.go
package swagger import ( "strconv" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/util" ) func rangeValueFromOptions(options []string) (minimum *float64, maximum *float64, exclusiveMinimum bool, exclusiveMaximum bool) { if len(options) == 0 { return nil, nil, false, false } for _, option := range options { if strings.HasPrefix(option, rangeFlag) { val := option[6:] start, end := val[0], val[len(val)-1] if start != '[' && start != '(' { return nil, nil, false, false } if end != ']' && end != ')' { return nil, nil, false, false } exclusiveMinimum = start == '(' exclusiveMaximum = end == ')' content := val[1 : len(val)-1] idxColon := strings.Index(content, ":") if idxColon < 0 { return nil, nil, false, false } var ( minStr, maxStr string minVal, maxVal *float64 ) minStr = util.TrimWhiteSpace(content[:idxColon]) if len(val) >= idxColon+1 { maxStr = util.TrimWhiteSpace(content[idxColon+1:]) } if len(minStr) > 0 { min, err := strconv.ParseFloat(minStr, 64) if err != nil { return nil, nil, false, false } minVal = &min } if len(maxStr) > 0 { max, err := strconv.ParseFloat(maxStr, 64) if err != nil { return nil, nil, false, false } maxVal = &max } return minVal, maxVal, exclusiveMinimum, exclusiveMaximum } } return nil, nil, false, false } func enumsValueFromOptions(options []string) []any { if len(options) == 0 { return []any{} } for _, option := range options { if strings.HasPrefix(option, enumFlag) { val := option[8:] fields := util.FieldsAndTrimSpace(val, func(r rune) bool { return r == '|' }) var resp = make([]any, 0, len(fields)) for _, field := range fields { resp = append(resp, field) } return resp } } return []any{} } func defValueFromOptions(ctx Context, options []string, apiType spec.Type) any { tp := sampleTypeFromGoType(ctx, apiType) return valueFromOptions(ctx, options, defFlag, tp) } func exampleValueFromOptions(ctx Context, options []string, apiType spec.Type) any { tp := sampleTypeFromGoType(ctx, apiType) val := valueFromOptions(ctx, options, exampleFlag, tp) if val != nil { return val } return defValueFromOptions(ctx, options, apiType) } func valueFromOptions(_ Context, options []string, key string, tp string) any { if len(options) == 0 { return nil } for _, option := range options { if strings.HasPrefix(option, key) { s := option[len(key):] switch tp { case swaggerTypeInteger: val, _ := strconv.ParseInt(s, 10, 64) return val case swaggerTypeBoolean: val, _ := strconv.ParseBool(s) return val case swaggerTypeNumber: val, _ := strconv.ParseFloat(s, 64) return val case swaggerTypeArray: return s case swaggerTypeString: return s default: return nil } } } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/vars.go
tools/goctl/api/swagger/vars.go
package swagger var ( tpMapper = map[string]string{ "uint8": swaggerTypeInteger, "uint16": swaggerTypeInteger, "uint32": swaggerTypeInteger, "uint64": swaggerTypeInteger, "int8": swaggerTypeInteger, "int16": swaggerTypeInteger, "int32": swaggerTypeInteger, "int64": swaggerTypeInteger, "int": swaggerTypeInteger, "uint": swaggerTypeInteger, "byte": swaggerTypeInteger, "float32": swaggerTypeNumber, "float64": swaggerTypeNumber, "string": swaggerTypeString, "bool": swaggerTypeBoolean, } commaRune = func(r rune) bool { return r == ',' } slashRune = func(r rune) bool { return r == '/' } )
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/context.go
tools/goctl/api/swagger/context.go
package swagger import ( "testing" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) type Context struct { UseDefinitions bool WrapCodeMsg bool BizCodeEnumDescription string } func testingContext(_ *testing.T) Context { return Context{} } func contextFromApi(info spec.Info) Context { if len(info.Properties) == 0 { return Context{} } return Context{ UseDefinitions: getBoolFromKVOrDefault(info.Properties, propertyKeyUseDefinitions, defaultValueOfPropertyUseDefinition), WrapCodeMsg: getBoolFromKVOrDefault(info.Properties, propertyKeyWrapCodeMsg, false), BizCodeEnumDescription: getStringFromKVOrDefault(info.Properties, propertyKeyBizCodeEnumDescription, "business code"), } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/command.go
tools/goctl/api/swagger/command.go
package swagger import ( "encoding/json" "errors" "os" "path/filepath" "strings" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/pkg/parser/api/parser" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" "gopkg.in/yaml.v2" ) var ( // VarStringAPI specifies the API filename. VarStringAPI string // VarStringDir specifies the directory to generate swagger file. VarStringDir string // VarStringFilename specifies the generated swagger file name without the extension. VarStringFilename string // VarBoolYaml specifies whether to generate a YAML file. VarBoolYaml bool ) func Command(_ *cobra.Command, _ []string) error { if len(VarStringAPI) == 0 { return errors.New("missing -api") } if len(VarStringDir) == 0 { return errors.New("missing -dir") } api, err := parser.Parse(VarStringAPI, "") if err != nil { return err } fillAllStructs(api) if err := api.Validate(); err != nil { return err } swagger, err := spec2Swagger(api) if err != nil { return err } data, err := json.MarshalIndent(swagger, "", " ") if err != nil { return err } err = pathx.MkdirIfNotExist(VarStringDir) if err != nil { return err } filename := VarStringFilename if filename == "" { base := filepath.Base(VarStringAPI) filename = strings.TrimSuffix(base, filepath.Ext(base)) } if VarBoolYaml { filePath := filepath.Join(VarStringDir, filename+".yaml") var jsonObj interface{} if err := yaml.Unmarshal(data, &jsonObj); err != nil { return err } data, err := yaml.Marshal(jsonObj) if err != nil { return err } return os.WriteFile(filePath, data, 0644) } // generate json swagger file filePath := filepath.Join(VarStringDir, filename+".json") return os.WriteFile(filePath, data, 0644) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/parameter.go
tools/goctl/api/swagger/parameter.go
package swagger import ( "net/http" "strings" "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func isRequestBodyJson(ctx Context, method string, tp apiSpec.Type) (string, bool) { // Support HTTP methods that commonly use request bodies with JSON // POST, PUT, PATCH are standard methods with bodies // DELETE can also have a body (though less common) method = strings.ToUpper(method) if method != http.MethodPost && method != http.MethodPut && method != http.MethodPatch && method != http.MethodDelete { return "", false } structType, ok := tp.(apiSpec.DefineStruct) if !ok { return "", false } var hasJsonField bool rangeMemberAndDo(ctx, structType, func(tag *apiSpec.Tags, required bool, member apiSpec.Member) { jsonTag, _ := tag.Get(tagJson) if !hasJsonField { hasJsonField = jsonTag != nil } }) return structType.RawName, hasJsonField } func parametersFromType(ctx Context, method string, tp apiSpec.Type) []spec.Parameter { if tp == nil { return []spec.Parameter{} } structType, ok := tp.(apiSpec.DefineStruct) if !ok { return []spec.Parameter{} } var ( resp []spec.Parameter properties = map[string]spec.Schema{} requiredFields []string ) rangeMemberAndDo(ctx, structType, func(tag *apiSpec.Tags, required bool, member apiSpec.Member) { headerTag, _ := tag.Get(tagHeader) hasHeader := headerTag != nil pathParameterTag, _ := tag.Get(tagPath) hasPathParameter := pathParameterTag != nil formTag, _ := tag.Get(tagForm) hasForm := formTag != nil jsonTag, _ := tag.Get(tagJson) hasJson := jsonTag != nil if hasHeader { minimum, maximum, exclusiveMinimum, exclusiveMaximum := rangeValueFromOptions(headerTag.Options) resp = append(resp, spec.Parameter{ CommonValidations: spec.CommonValidations{ Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enumsValueFromOptions(headerTag.Options), }, SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, member.Type), Default: defValueFromOptions(ctx, headerTag.Options, member.Type), Items: sampleItemsFromGoType(ctx, member.Type), }, ParamProps: spec.ParamProps{ In: paramsInHeader, Name: headerTag.Name, Description: formatComment(member.Comment), Required: required, }, }) } if hasPathParameter { minimum, maximum, exclusiveMinimum, exclusiveMaximum := rangeValueFromOptions(pathParameterTag.Options) resp = append(resp, spec.Parameter{ CommonValidations: spec.CommonValidations{ Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enumsValueFromOptions(pathParameterTag.Options), }, SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, member.Type), Default: defValueFromOptions(ctx, pathParameterTag.Options, member.Type), Items: sampleItemsFromGoType(ctx, member.Type), }, ParamProps: spec.ParamProps{ In: paramsInPath, Name: pathParameterTag.Name, Description: formatComment(member.Comment), Required: required, }, }) } if hasForm { minimum, maximum, exclusiveMinimum, exclusiveMaximum := rangeValueFromOptions(formTag.Options) if strings.EqualFold(method, http.MethodGet) { resp = append(resp, spec.Parameter{ CommonValidations: spec.CommonValidations{ Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enumsValueFromOptions(formTag.Options), }, SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, member.Type), Default: defValueFromOptions(ctx, formTag.Options, member.Type), Items: sampleItemsFromGoType(ctx, member.Type), }, ParamProps: spec.ParamProps{ In: paramsInQuery, Name: formTag.Name, Description: formatComment(member.Comment), Required: required, AllowEmptyValue: !required, }, }) } else { resp = append(resp, spec.Parameter{ CommonValidations: spec.CommonValidations{ Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enumsValueFromOptions(formTag.Options), }, SimpleSchema: spec.SimpleSchema{ Type: sampleTypeFromGoType(ctx, member.Type), Default: defValueFromOptions(ctx, formTag.Options, member.Type), Items: sampleItemsFromGoType(ctx, member.Type), }, ParamProps: spec.ParamProps{ In: paramsInForm, Name: formTag.Name, Description: formatComment(member.Comment), Required: required, AllowEmptyValue: !required, }, }) } } if hasJson { minimum, maximum, exclusiveMinimum, exclusiveMaximum := rangeValueFromOptions(jsonTag.Options) if required { requiredFields = append(requiredFields, jsonTag.Name) } var schema = spec.Schema{ SwaggerSchemaProps: spec.SwaggerSchemaProps{ Example: exampleValueFromOptions(ctx, jsonTag.Options, member.Type), }, SchemaProps: spec.SchemaProps{ Description: formatComment(member.Comment), Type: typeFromGoType(ctx, member.Type), Default: defValueFromOptions(ctx, jsonTag.Options, member.Type), Maximum: maximum, ExclusiveMaximum: exclusiveMaximum, Minimum: minimum, ExclusiveMinimum: exclusiveMinimum, Enum: enumsValueFromOptions(jsonTag.Options), AdditionalProperties: mapFromGoType(ctx, member.Type), }, } switch sampleTypeFromGoType(ctx, member.Type) { case swaggerTypeArray: schema.Items = itemsFromGoType(ctx, member.Type) case swaggerTypeObject: p, r := propertiesFromType(ctx, member.Type) schema.Properties = p schema.Required = r } properties[jsonTag.Name] = schema } }) if len(properties) > 0 { if ctx.UseDefinitions { structName, ok := isRequestBodyJson(ctx, method, tp) if ok { resp = append(resp, spec.Parameter{ ParamProps: spec.ParamProps{ In: paramsInBody, Name: paramsInBody, Required: true, Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Ref: spec.MustCreateRef(getRefName(structName)), }, }, }, }) } } else { resp = append(resp, spec.Parameter{ ParamProps: spec.ParamProps{ In: paramsInBody, Name: paramsInBody, Required: true, Schema: &spec.Schema{ SchemaProps: spec.SchemaProps{ Type: typeFromGoType(ctx, structType), Properties: properties, Required: requiredFields, }, }, }, }) } } return resp }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/annotation.go
tools/goctl/api/swagger/annotation.go
package swagger import ( "strconv" "github.com/zeromicro/go-zero/tools/goctl/util" "google.golang.org/grpc/metadata" ) func getBoolFromKVOrDefault(properties map[string]string, key string, def bool) bool { return getOrDefault(properties, key, def, func(str string, def bool) bool { res, err := strconv.ParseBool(str) if err != nil { return def } return res }) } func getFirstUsableString(def ...string) string { if len(def) == 0 { return "" } for _, val := range def { // Try to unquote if it's a quoted string if str, err := strconv.Unquote(val); err == nil && len(str) != 0 { return str } // Otherwise, use the value as-is if it's not empty if len(val) != 0 { return val } } return "" } func getListFromInfoOrDefault(properties map[string]string, key string, def []string) []string { return getOrDefault(properties, key, def, func(str string, def []string) []string { resp := util.FieldsAndTrimSpace(str, commaRune) if len(resp) == 0 { return def } return resp }) } // getOrDefault abstracts the common logic for fetching, unquoting, and defaulting. func getOrDefault[T any](properties map[string]string, key string, def T, convert func(string, T) T) T { if len(properties) == 0 { return def } md := metadata.New(properties) val := md.Get(key) if len(val) == 0 { return def } str := val[0] if unquoted, err := strconv.Unquote(str); err == nil { str = unquoted } if len(str) == 0 { return def } return convert(str, def) } func getStringFromKVOrDefault(properties map[string]string, key string, def string) string { return getOrDefault(properties, key, def, func(str string, def string) string { return str }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/swagger/definition.go
tools/goctl/api/swagger/definition.go
package swagger import ( "github.com/go-openapi/spec" apiSpec "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func definitionsFromTypes(ctx Context, types []apiSpec.Type) spec.Definitions { if !ctx.UseDefinitions { return nil } definitions := make(spec.Definitions) for _, tp := range types { typeName := tp.Name() definitions[typeName] = schemaFromType(ctx, tp) } return definitions } func schemaFromType(ctx Context, tp apiSpec.Type) spec.Schema { p, r := propertiesFromType(ctx, tp) props := spec.SchemaProps{ Type: typeFromGoType(ctx, tp), Properties: p, AdditionalProperties: mapFromGoType(ctx, tp), Items: itemsFromGoType(ctx, tp), Required: r, } return spec.Schema{ SchemaProps: props, } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/apigen/gen.go
tools/goctl/api/apigen/gen.go
package apigen import ( _ "embed" "errors" "fmt" "html/template" "path/filepath" "strings" "github.com/gookit/color" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) //go:embed api.tpl var apiTemplate string var ( // VarStringOutput describes the output. VarStringOutput string // VarStringHome describes the goctl home. VarStringHome string // VarStringRemote describes the remote git repository. VarStringRemote string // VarStringBranch describes the git branch. VarStringBranch string ) // CreateApiTemplate create api template file func CreateApiTemplate(_ *cobra.Command, _ []string) error { apiFile := VarStringOutput if len(apiFile) == 0 { return errors.New("missing -o") } fp, err := pathx.CreateIfNotExist(apiFile) if err != nil { return err } defer fp.Close() if len(VarStringRemote) > 0 { repo, _ := util.CloneIntoGitHome(VarStringRemote, VarStringBranch) if len(repo) > 0 { VarStringHome = repo } } if len(VarStringHome) > 0 { pathx.RegisterGoctlHome(VarStringHome) } text, err := pathx.LoadTemplate(category, apiTemplateFile, apiTemplate) if err != nil { return err } baseName := pathx.FileNameWithoutExt(filepath.Base(apiFile)) if strings.HasSuffix(strings.ToLower(baseName), "-api") { baseName = baseName[:len(baseName)-4] } else if strings.HasSuffix(strings.ToLower(baseName), "api") { baseName = baseName[:len(baseName)-3] } t := template.Must(template.New("etcTemplate").Parse(text)) if err := t.Execute(fp, map[string]string{ "gitUser": getGitName(), "gitEmail": getGitEmail(), "serviceName": baseName + "-api", }); err != nil { return err } fmt.Println(color.Green.Render("Done.")) return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/apigen/util.go
tools/goctl/api/apigen/util.go
package apigen import ( "os/exec" "strings" ) func getGitName() string { cmd := exec.Command("git", "config", "user.name") out, err := cmd.CombinedOutput() if err != nil { return "" } return strings.TrimSpace(string(out)) } func getGitEmail() string { cmd := exec.Command("git", "config", "user.email") out, err := cmd.CombinedOutput() if err != nil { return "" } return strings.TrimSpace(string(out)) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/apigen/template.go
tools/goctl/api/apigen/template.go
package apigen import ( "fmt" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const ( category = "api" apiTemplateFile = "template.tpl" ) var templates = map[string]string{ apiTemplateFile: apiTemplate, } // Category returns the category of the api files. func Category() string { return category } // Clean cleans the generated deployment files. func Clean() error { return pathx.Clean(category) } // GenTemplates generates api template files. func GenTemplates() error { return pathx.InitTemplates(category, templates) } // RevertTemplate reverts the given template file to the default value. func RevertTemplate(name string) error { content, ok := templates[name] if !ok { return fmt.Errorf("%s: no such file name", name) } return pathx.CreateTemplate(category, name, content) } // Update updates the template files to the templates built in current goctl. func Update() error { err := Clean() if err != nil { return err } return pathx.InitTemplates(category, templates) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genmiddleware.go
tools/goctl/api/gogen/genmiddleware.go
package gogen import ( _ "embed" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util/format" ) //go:embed middleware.tpl var middlewareImplementCode string func genMiddleware(dir string, cfg *config.Config, api *spec.ApiSpec) error { middlewares := getMiddleware(api) for _, item := range middlewares { middlewareFilename := strings.TrimSuffix(strings.ToLower(item), "middleware") + "_middleware" filename, err := format.FileNamingFormat(cfg.NamingFormat, middlewareFilename) if err != nil { return err } name := strings.TrimSuffix(item, "Middleware") + "Middleware" err = genFile(fileGenConfig{ dir: dir, subdir: middlewareDir, filename: filename + ".go", templateName: "contextTemplate", category: category, templateFile: middlewareImplementCodeFile, builtinTemplate: middlewareImplementCode, data: map[string]string{ "name": strings.Title(name), "version": version.BuildVersion, }, }) if err != nil { return err } } return nil }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genconfig.go
tools/goctl/api/gogen/genconfig.go
package gogen import ( _ "embed" "fmt" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/vars" ) const ( configFile = "config" jwtTemplate = ` struct { AccessSecret string AccessExpire int64 } ` jwtTransTemplate = ` struct { Secret string PrevSecret string } ` ) //go:embed config.tpl var configTemplate string func genConfig(dir, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error { filename, err := format.FileNamingFormat(cfg.NamingFormat, configFile) if err != nil { return err } authNames := getAuths(api) auths := make([]string, 0, len(authNames)) for _, item := range authNames { auths = append(auths, fmt.Sprintf("%s %s", item, jwtTemplate)) } jwtTransNames := getJwtTrans(api) jwtTransList := make([]string, 0, len(jwtTransNames)) for _, item := range jwtTransNames { jwtTransList = append(jwtTransList, fmt.Sprintf("%s %s", item, jwtTransTemplate)) } authImportStr := fmt.Sprintf("\"%s/rest\"", vars.ProjectOpenSourceURL) return genFile(fileGenConfig{ dir: dir, subdir: configDir, filename: filename + ".go", templateName: "configTemplate", category: category, templateFile: configTemplateFile, builtinTemplate: configTemplate, data: map[string]string{ "authImport": authImportStr, "auth": strings.Join(auths, "\n"), "jwtTrans": strings.Join(jwtTransList, "\n"), "projectPkg": projectPkg, "version": version.BuildVersion, }, }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gencomment_test.go
tools/goctl/api/gogen/gencomment_test.go
package gogen import ( "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/zeromicro/go-zero/tools/goctl/internal/version" ) // TestGenerationComments verifies that all generated files have appropriate generation comments func TestGenerationComments(t *testing.T) { // Create a temporary directory for our test tempDir, err := os.MkdirTemp("", "goctl_test_") require.NoError(t, err) defer os.RemoveAll(tempDir) // Create a simple API spec for testing apiContent := ` syntax = "v1" type HelloRequest { Name string ` + "`json:\"name\"`" + ` } type HelloResponse { Message string ` + "`json:\"message\"`" + ` } service hello-api { @handler helloHandler post /hello (HelloRequest) returns (HelloResponse) }` // Write the API spec to a temporary file apiFile := filepath.Join(tempDir, "test.api") err = os.WriteFile(apiFile, []byte(apiContent), 0644) require.NoError(t, err) // Parse and generate the API files using the correct function signature err = DoGenProject(apiFile, tempDir, "gozero", false) require.NoError(t, err) // Define expected files and their comment types expectedFiles := map[string]string{ // Files that should have "DO NOT EDIT" comments (regenerated files) "internal/types/types.go": "DO NOT EDIT", // Files that should have "Safe to edit" comments (scaffolded files) "internal/handler/hellohandler.go": "Safe to edit", "internal/config/config.go": "Safe to edit", "hello.go": "Safe to edit", // main file "internal/svc/servicecontext.go": "Safe to edit", "internal/logic/hellologic.go": "Safe to edit", } // Check each file for the correct generation comment for filePath, expectedCommentType := range expectedFiles { fullPath := filepath.Join(tempDir, filePath) // Skip if file doesn't exist (some files might not be generated in all cases) if _, err := os.Stat(fullPath); os.IsNotExist(err) { t.Logf("File %s does not exist, skipping", filePath) continue } content, err := os.ReadFile(fullPath) require.NoError(t, err, "Failed to read file: %s", filePath) contentStr := string(content) lines := strings.Split(contentStr, "\n") // Check that the file starts with proper generation comments require.GreaterOrEqual(t, len(lines), 2, "File %s should have at least 2 lines", filePath) if expectedCommentType == "DO NOT EDIT" { assert.Contains(t, lines[0], "// Code generated by goctl. DO NOT EDIT.", "File %s should have 'DO NOT EDIT' comment as first line", filePath) } else if expectedCommentType == "Safe to edit" { assert.Contains(t, lines[0], "// Code scaffolded by goctl. Safe to edit.", "File %s should have 'Safe to edit' comment as first line", filePath) } // Check that the second line contains the version assert.Contains(t, lines[1], "// goctl", "File %s should have version comment as second line", filePath) assert.Contains(t, lines[1], version.BuildVersion, "File %s should contain version %s in second line", filePath, version.BuildVersion) } } // TestRoutesGenerationComment verifies routes files have "DO NOT EDIT" comment func TestRoutesGenerationComment(t *testing.T) { // Create a temporary directory for our test tempDir, err := os.MkdirTemp("", "goctl_routes_test_") require.NoError(t, err) defer os.RemoveAll(tempDir) // Create an API spec with multiple handlers to ensure routes file is generated apiContent := ` syntax = "v1" type HelloRequest { Name string ` + "`json:\"name\"`" + ` } type HelloResponse { Message string ` + "`json:\"message\"`" + ` } service hello-api { @handler helloHandler post /hello (HelloRequest) returns (HelloResponse) @handler worldHandler get /world returns (HelloResponse) }` // Write the API spec to a temporary file apiFile := filepath.Join(tempDir, "test.api") err = os.WriteFile(apiFile, []byte(apiContent), 0644) require.NoError(t, err) // Generate the API files using the correct function signature err = DoGenProject(apiFile, tempDir, "gozero", false) require.NoError(t, err) // Check the routes file specifically routesFile := filepath.Join(tempDir, "internal/handler/routes.go") if _, err := os.Stat(routesFile); os.IsNotExist(err) { t.Skip("Routes file not generated, skipping test") return } content, err := os.ReadFile(routesFile) require.NoError(t, err, "Failed to read routes.go") contentStr := string(content) lines := strings.Split(contentStr, "\n") // Check that routes.go has "DO NOT EDIT" comment require.GreaterOrEqual(t, len(lines), 2, "Routes file should have at least 2 lines") assert.Contains(t, lines[0], "// Code generated by goctl. DO NOT EDIT.", "Routes file should have 'DO NOT EDIT' comment") assert.Contains(t, lines[1], "// goctl", "Routes file should have version comment") assert.Contains(t, lines[1], version.BuildVersion, "Routes file should contain version %s", version.BuildVersion) } // TestVersionInTemplateData verifies that version is correctly passed to templates func TestVersionInTemplateData(t *testing.T) { // Test that BuildVersion is available assert.NotEmpty(t, version.BuildVersion, "BuildVersion should not be empty") } // TestCommentsFollowGoStandards verifies our comments follow Go community standards func TestCommentsFollowGoStandards(t *testing.T) { // Test the format of our generation comments doNotEditComment := "// Code generated by goctl. DO NOT EDIT." safeToEditComment := "// Code scaffolded by goctl. Safe to edit." // Both should be valid Go comments assert.True(t, strings.HasPrefix(doNotEditComment, "//"), "DO NOT EDIT comment should start with //") assert.True(t, strings.HasPrefix(safeToEditComment, "//"), "Safe to edit comment should start with //") // Should contain key information assert.Contains(t, doNotEditComment, "goctl", "DO NOT EDIT comment should mention goctl") assert.Contains(t, safeToEditComment, "goctl", "Safe to edit comment should mention goctl") assert.Contains(t, doNotEditComment, "DO NOT EDIT", "Should clearly state DO NOT EDIT") assert.Contains(t, safeToEditComment, "Safe to edit", "Should clearly state Safe to edit") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genlogictest.go
tools/goctl/api/gogen/genlogictest.go
package gogen import ( _ "embed" "fmt" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) //go:embed logic_test.tpl var logicTestTemplate string func genLogicTest(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error { for _, g := range api.Service.Groups { for _, r := range g.Routes { err := genLogicTestByRoute(dir, rootPkg, projectPkg, cfg, g, r) if err != nil { return err } } } return nil } func genLogicTestByRoute(dir, rootPkg, projectPkg string, cfg *config.Config, group spec.Group, route spec.Route) error { logic := getLogicName(route) goFile, err := format.FileNamingFormat(cfg.NamingFormat, logic) if err != nil { return err } imports := genLogicTestImports(route, rootPkg) var responseString string var returnString string var requestString string var requestType string if len(route.ResponseTypeName()) > 0 { resp := responseGoTypeName(route, typesPacket) responseString = "(resp " + resp + ", err error)" returnString = "return" } else { responseString = "error" returnString = "return nil" } if len(route.RequestTypeName()) > 0 { requestString = "req *" + requestGoTypeName(route, typesPacket) requestType = requestGoTypeName(route, typesPacket) } subDir := getLogicFolderPath(group, route) return genFile(fileGenConfig{ dir: dir, subdir: subDir, filename: goFile + "_test.go", templateName: "logicTestTemplate", category: category, templateFile: logicTestTemplateFile, builtinTemplate: logicTestTemplate, data: map[string]any{ "pkgName": subDir[strings.LastIndex(subDir, "/")+1:], "imports": imports, "logic": strings.Title(logic), "function": strings.Title(strings.TrimSuffix(logic, "Logic")), "responseType": responseString, "returnString": returnString, "request": requestString, "hasRequest": len(requestType) > 0, "hasResponse": len(route.ResponseTypeName()) > 0, "requestType": requestType, "hasDoc": len(route.JoinedDoc()) > 0, "doc": getDoc(route.JoinedDoc()), "projectPkg": projectPkg, "version": version.BuildVersion, }, }) } func genLogicTestImports(route spec.Route, parentPkg string) string { var imports []string //imports = append(imports, `"context"`+"\n") imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir))) imports = append(imports, fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, configDir))) if shallImportTypesPackage(route) { imports = append(imports, fmt.Sprintf("\"%s\"\n", pathx.JoinPackages(parentPkg, typesDir))) } //imports = append(imports, fmt.Sprintf("\"%s/core/logx\"", vars.ProjectOpenSourceURL)) return strings.Join(imports, "\n\t") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genroutes_test.go
tools/goctl/api/gogen/genroutes_test.go
package gogen import ( "testing" "time" "github.com/zeromicro/go-zero/tools/goctl/api/spec" ) func Test_formatDuration(t *testing.T) { tests := []struct { duration time.Duration expected string }{ {0, "0 * time.Nanosecond"}, {time.Nanosecond, "1 * time.Nanosecond"}, {100 * time.Nanosecond, "100 * time.Nanosecond"}, {500 * time.Microsecond, "500 * time.Microsecond"}, {2 * time.Millisecond, "2 * time.Millisecond"}, {time.Second, "1000 * time.Millisecond"}, } for _, test := range tests { result := formatDuration(test.duration) if result != test.expected { t.Errorf("formatDuration(%v) = %v; want %v", test.duration, result, test.expected) } } } func TestSSESupport(t *testing.T) { // Test API spec with SSE enabled apiSpec := &spec.ApiSpec{ Service: spec.Service{ Groups: []spec.Group{ { Annotation: spec.Annotation{ Properties: map[string]string{ "sse": "true", "prefix": "/api/v1", }, }, Routes: []spec.Route{ { Method: "get", Path: "/events", Handler: "StreamEvents", }, }, }, }, }, } groups, err := getRoutes(apiSpec) if err != nil { t.Fatalf("getRoutes failed: %v", err) } if len(groups) != 1 { t.Fatalf("Expected 1 group, got %d", len(groups)) } group := groups[0] if !group.sseEnabled { t.Error("Expected SSE to be enabled") } if group.prefix != "/api/v1" { t.Errorf("Expected prefix '/api/v1', got '%s'", group.prefix) } if len(group.routes) != 1 { t.Fatalf("Expected 1 route, got %d", len(group.routes)) } route := group.routes[0] if route.method != "http.MethodGet" { t.Errorf("Expected method 'http.MethodGet', got '%s'", route.method) } if route.path != "/events" { t.Errorf("Expected path '/events', got '%s'", route.path) } } func TestSSEWithOtherFeatures(t *testing.T) { // Test API spec with SSE and other features apiSpec := &spec.ApiSpec{ Service: spec.Service{ Groups: []spec.Group{ { Annotation: spec.Annotation{ Properties: map[string]string{ "sse": "true", "jwt": "Auth", "signature": "true", "prefix": "/api/v1", "timeout": "30s", "middleware": "AuthMiddleware,LogMiddleware", }, }, Routes: []spec.Route{ { Method: "get", Path: "/events", Handler: "StreamEvents", }, }, }, }, }, } groups, err := getRoutes(apiSpec) if err != nil { t.Fatalf("getRoutes failed: %v", err) } if len(groups) != 1 { t.Fatalf("Expected 1 group, got %d", len(groups)) } group := groups[0] // Verify all features are enabled if !group.sseEnabled { t.Error("Expected SSE to be enabled") } if !group.jwtEnabled { t.Error("Expected JWT to be enabled") } if !group.signatureEnabled { t.Error("Expected signature to be enabled") } if group.authName != "Auth" { t.Errorf("Expected authName 'Auth', got '%s'", group.authName) } if group.prefix != "/api/v1" { t.Errorf("Expected prefix '/api/v1', got '%s'", group.prefix) } if group.timeout != "30s" { t.Errorf("Expected timeout '30s', got '%s'", group.timeout) } expectedMiddlewares := []string{"AuthMiddleware", "LogMiddleware"} if len(group.middlewares) != len(expectedMiddlewares) { t.Errorf("Expected %d middlewares, got %d", len(expectedMiddlewares), len(group.middlewares)) } for i, expected := range expectedMiddlewares { if group.middlewares[i] != expected { t.Errorf("Expected middleware[%d] '%s', got '%s'", i, expected, group.middlewares[i]) } } } func TestSSEDisabled(t *testing.T) { // Test API spec without SSE apiSpec := &spec.ApiSpec{ Service: spec.Service{ Groups: []spec.Group{ { Annotation: spec.Annotation{ Properties: map[string]string{ "prefix": "/api/v1", }, }, Routes: []spec.Route{ { Method: "get", Path: "/status", Handler: "GetStatus", }, }, }, }, }, } groups, err := getRoutes(apiSpec) if err != nil { t.Fatalf("getRoutes failed: %v", err) } if len(groups) != 1 { t.Fatalf("Expected 1 group, got %d", len(groups)) } group := groups[0] if group.sseEnabled { t.Error("Expected SSE to be disabled") } }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genhandlers.go
tools/goctl/api/gogen/genhandlers.go
package gogen import ( _ "embed" "fmt" "path" "strings" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/format" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const defaultLogicPackage = "logic" var ( //go:embed handler.tpl handlerTemplate string //go:embed sse_handler.tpl sseHandlerTemplate string ) func genHandler(dir, rootPkg, projectPkg string, cfg *config.Config, group spec.Group, route spec.Route) error { handler := getHandlerName(route) handlerPath := getHandlerFolderPath(group, route) pkgName := handlerPath[strings.LastIndex(handlerPath, "/")+1:] logicName := defaultLogicPackage if handlerPath != handlerDir { handler = strings.Title(handler) logicName = pkgName } filename, err := format.FileNamingFormat(cfg.NamingFormat, handler) if err != nil { return err } var builtinTemplate = handlerTemplate var templateFile = handlerTemplateFile sse := group.GetAnnotation("sse") if sse == "true" { builtinTemplate = sseHandlerTemplate templateFile = sseHandlerTemplateFile } return genFile(fileGenConfig{ dir: dir, subdir: getHandlerFolderPath(group, route), filename: filename + ".go", templateName: "handlerTemplate", category: category, templateFile: templateFile, builtinTemplate: builtinTemplate, data: map[string]any{ "PkgName": pkgName, "ImportPackages": genHandlerImports(group, route, rootPkg), "HandlerName": handler, "RequestType": util.Title(route.RequestTypeName()), "ResponseType": responseGoTypeName(route, typesPacket), "LogicName": logicName, "LogicType": strings.Title(getLogicName(route)), "Call": strings.Title(strings.TrimSuffix(handler, "Handler")), "HasResp": len(route.ResponseTypeName()) > 0, "HasRequest": len(route.RequestTypeName()) > 0, "HasDoc": len(route.JoinedDoc()) > 0, "Doc": getDoc(route.JoinedDoc()), "projectPkg": projectPkg, "version": version.BuildVersion, }, }) } func genHandlers(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error { for _, group := range api.Service.Groups { for _, route := range group.Routes { if err := genHandler(dir, rootPkg, projectPkg, cfg, group, route); err != nil { return err } } } return nil } func genHandlerImports(group spec.Group, route spec.Route, parentPkg string) string { imports := []string{ fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, getLogicFolderPath(group, route))), fmt.Sprintf("\"%s\"", pathx.JoinPackages(parentPkg, contextDir)), } sse := group.GetAnnotation("sse") if len(route.RequestTypeName()) > 0 || sse == "true" { imports = append(imports, fmt.Sprintf("\"%s\"\n", pathx.JoinPackages(parentPkg, typesDir))) } return strings.Join(imports, "\n\t") } func getHandlerBaseName(route spec.Route) (string, error) { handler := route.Handler handler = strings.TrimSpace(handler) handler = strings.TrimSuffix(handler, "handler") handler = strings.TrimSuffix(handler, "Handler") return handler, nil } func getHandlerFolderPath(group spec.Group, route spec.Route) string { folder := route.GetAnnotation(groupProperty) if len(folder) == 0 { folder = group.GetAnnotation(groupProperty) if len(folder) == 0 { return handlerDir } } folder = strings.TrimPrefix(folder, "/") folder = strings.TrimSuffix(folder, "/") return path.Join(handlerDir, folder) } func getHandlerName(route spec.Route) string { handler, err := getHandlerBaseName(route) if err != nil { panic(err) } return handler + "Handler" } func getLogicName(route spec.Route) string { handler, err := getHandlerBaseName(route) if err != nil { panic(err) } return handler + "Logic" }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gensvctest.go
tools/goctl/api/gogen/gensvctest.go
package gogen import ( _ "embed" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/internal/version" "github.com/zeromicro/go-zero/tools/goctl/util/format" ) //go:embed svc_test.tpl var svcTestTemplate string func genServiceContextTest(dir, rootPkg, projectPkg string, cfg *config.Config, api *spec.ApiSpec) error { filename, err := format.FileNamingFormat(cfg.NamingFormat, contextFilename) if err != nil { return err } return genFile(fileGenConfig{ dir: dir, subdir: contextDir, filename: filename + "_test.go", templateName: "svcTestTemplate", category: category, templateFile: svcTestTemplateFile, builtinTemplate: svcTestTemplate, data: map[string]any{ "projectPkg": projectPkg, "version": version.BuildVersion, }, }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/genetc.go
tools/goctl/api/gogen/genetc.go
package gogen import ( _ "embed" "fmt" "strconv" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/util/format" ) const ( defaultPort = 8888 etcDir = "etc" ) //go:embed etc.tpl var etcTemplate string func genEtc(dir string, cfg *config.Config, api *spec.ApiSpec) error { filename, err := format.FileNamingFormat(cfg.NamingFormat, api.Service.Name) if err != nil { return err } service := api.Service host := "0.0.0.0" port := strconv.Itoa(defaultPort) return genFile(fileGenConfig{ dir: dir, subdir: etcDir, filename: fmt.Sprintf("%s.yaml", filename), templateName: "etcTemplate", category: category, templateFile: etcTemplateFile, builtinTemplate: etcTemplate, data: map[string]string{ "serviceName": service.Name, "host": host, "port": port, }, }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/gen.go
tools/goctl/api/gogen/gen.go
package gogen import ( "errors" "fmt" "os" "path" "path/filepath" "strconv" "strings" "sync" "time" "github.com/gookit/color" "github.com/spf13/cobra" "github.com/zeromicro/go-zero/core/logx" apiformat "github.com/zeromicro/go-zero/tools/goctl/api/format" "github.com/zeromicro/go-zero/tools/goctl/api/parser" apiutil "github.com/zeromicro/go-zero/tools/goctl/api/util" "github.com/zeromicro/go-zero/tools/goctl/config" "github.com/zeromicro/go-zero/tools/goctl/pkg/golang" "github.com/zeromicro/go-zero/tools/goctl/util" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) const tmpFile = "%s-%d" var ( tmpDir = path.Join(os.TempDir(), "goctl") // VarStringDir describes the directory. VarStringDir string // VarStringAPI describes the API. VarStringAPI string // VarStringHome describes the go home. VarStringHome string // VarStringRemote describes the remote git repository. VarStringRemote string // VarStringBranch describes the branch. VarStringBranch string // VarStringStyle describes the style of output files. VarStringStyle string VarBoolWithTest bool // VarBoolTypeGroup describes whether to group types. VarBoolTypeGroup bool ) // GoCommand gen go project files from command line func GoCommand(_ *cobra.Command, _ []string) error { apiFile := VarStringAPI dir := VarStringDir namingStyle := VarStringStyle home := VarStringHome remote := VarStringRemote branch := VarStringBranch withTest := VarBoolWithTest if len(remote) > 0 { repo, _ := util.CloneIntoGitHome(remote, branch) if len(repo) > 0 { home = repo } } if len(home) > 0 { pathx.RegisterGoctlHome(home) } if len(apiFile) == 0 { return errors.New("missing -api") } if len(dir) == 0 { return errors.New("missing -dir") } return DoGenProject(apiFile, dir, namingStyle, withTest) } // DoGenProject gen go project files with api file func DoGenProject(apiFile, dir, style string, withTest bool) error { return DoGenProjectWithModule(apiFile, dir, "", style, withTest) } // DoGenProjectWithModule gen go project files with api file using custom module name func DoGenProjectWithModule(apiFile, dir, moduleName, style string, withTest bool) error { api, err := parser.Parse(apiFile) if err != nil { return err } if err := api.Validate(); err != nil { return err } cfg, err := config.NewConfig(style) if err != nil { return err } logx.Must(pathx.MkdirIfNotExist(dir)) var rootPkg, projectPkg string if len(moduleName) > 0 { rootPkg, projectPkg, err = golang.GetParentPackageWithModule(dir, moduleName) } else { rootPkg, projectPkg, err = golang.GetParentPackage(dir) } if err != nil { return err } logx.Must(genEtc(dir, cfg, api)) logx.Must(genConfig(dir, projectPkg, cfg, api)) logx.Must(genMain(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genServiceContext(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genTypes(dir, cfg, api)) logx.Must(genRoutes(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genHandlers(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genLogic(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genMiddleware(dir, cfg, api)) if withTest { logx.Must(genHandlersTest(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genLogicTest(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genServiceContextTest(dir, rootPkg, projectPkg, cfg, api)) logx.Must(genIntegrationTest(dir, rootPkg, projectPkg, cfg, api)) } if err := backupAndSweep(apiFile); err != nil { return err } if err := apiformat.ApiFormatByPath(apiFile, false); err != nil { return err } fmt.Println(color.Green.Render("Done.")) return nil } func backupAndSweep(apiFile string) error { var err error var wg sync.WaitGroup wg.Add(2) _ = os.MkdirAll(tmpDir, os.ModePerm) go func() { _, fileName := filepath.Split(apiFile) _, e := apiutil.Copy(apiFile, fmt.Sprintf(path.Join(tmpDir, tmpFile), fileName, time.Now().Unix())) if e != nil { err = e } wg.Done() }() go func() { if e := sweep(); e != nil { err = e } wg.Done() }() wg.Wait() return err } func sweep() error { keepTime := time.Now().AddDate(0, 0, -7) return filepath.Walk(tmpDir, func(fpath string, info os.FileInfo, err error) error { if info.IsDir() { return nil } pos := strings.LastIndexByte(info.Name(), '-') if pos > 0 { timestamp := info.Name()[pos+1:] seconds, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { // print error and ignore fmt.Println(color.Red.Sprintf("sweep ignored file: %s", fpath)) return nil } tm := time.Unix(seconds, 0) if tm.Before(keepTime) { if err := os.RemoveAll(fpath); err != nil { fmt.Println(color.Red.Sprintf("failed to remove file: %s", fpath)) return err } } } return nil }) }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false
zeromicro/go-zero
https://github.com/zeromicro/go-zero/blob/8e7e5695eb2095917864b5d6615dab4c90bde3ac/tools/goctl/api/gogen/util.go
tools/goctl/api/gogen/util.go
package gogen import ( "bytes" "fmt" "io" "strings" "text/template" "github.com/zeromicro/go-zero/core/collection" "github.com/zeromicro/go-zero/tools/goctl/api/spec" "github.com/zeromicro/go-zero/tools/goctl/api/util" "github.com/zeromicro/go-zero/tools/goctl/pkg/golang" "github.com/zeromicro/go-zero/tools/goctl/util/pathx" ) type fileGenConfig struct { dir string subdir string filename string templateName string category string templateFile string builtinTemplate string data any } func genFile(c fileGenConfig) error { fp, created, err := util.MaybeCreateFile(c.dir, c.subdir, c.filename) if err != nil { return err } if !created { return nil } defer fp.Close() var text string if len(c.category) == 0 || len(c.templateFile) == 0 { text = c.builtinTemplate } else { text, err = pathx.LoadTemplate(c.category, c.templateFile, c.builtinTemplate) if err != nil { return err } } t := template.Must(template.New(c.templateName).Parse(text)) buffer := new(bytes.Buffer) err = t.Execute(buffer, c.data) if err != nil { return err } code := golang.FormatCode(buffer.String()) _, err = fp.WriteString(code) return err } func writeProperty(writer io.Writer, name, tag, comment string, tp spec.Type, indent int) error { util.WriteIndent(writer, indent) var ( err error isNestedStruct bool ) structType, ok := tp.(spec.NestedStruct) if ok { isNestedStruct = true } if len(comment) > 0 { comment = strings.TrimPrefix(comment, "//") comment = "//" + comment } if isNestedStruct { _, err = fmt.Fprintf(writer, "%s struct {\n", strings.Title(name)) if err != nil { return err } if err := writeMember(writer, structType.Members); err != nil { return err } _, err := fmt.Fprintf(writer, "} %s", tag) if err != nil { return err } if len(comment) > 0 { _, err = fmt.Fprintf(writer, " %s", comment) if err != nil { return err } } _, err = fmt.Fprint(writer, "\n") if err != nil { return err } } else { if len(comment) > 0 { _, err = fmt.Fprintf(writer, "%s %s %s %s\n", strings.Title(name), tp.Name(), tag, comment) if err != nil { return err } } else { _, err = fmt.Fprintf(writer, "%s %s %s\n", strings.Title(name), tp.Name(), tag) if err != nil { return err } } } return nil } func getAuths(api *spec.ApiSpec) []string { authNames := collection.NewSet[string]() for _, g := range api.Service.Groups { jwt := g.GetAnnotation("jwt") if len(jwt) > 0 { authNames.Add(jwt) } } return authNames.Keys() } func getJwtTrans(api *spec.ApiSpec) []string { jwtTransList := collection.NewSet[string]() for _, g := range api.Service.Groups { jt := g.GetAnnotation(jwtTransKey) if len(jt) > 0 { jwtTransList.Add(jt) } } return jwtTransList.Keys() } func getMiddleware(api *spec.ApiSpec) []string { result := collection.NewSet[string]() for _, g := range api.Service.Groups { middleware := g.GetAnnotation("middleware") if len(middleware) > 0 { for _, item := range strings.Split(middleware, ",") { result.Add(strings.TrimSpace(item)) } } } return result.Keys() } func responseGoTypeName(r spec.Route, pkg ...string) string { if r.ResponseType == nil { return "" } resp := golangExpr(r.ResponseType, pkg...) switch r.ResponseType.(type) { case spec.DefineStruct: if !strings.HasPrefix(resp, "*") { return "*" + resp } } return resp } func requestGoTypeName(r spec.Route, pkg ...string) string { if r.RequestType == nil { return "" } return golangExpr(r.RequestType, pkg...) } func golangExpr(ty spec.Type, pkg ...string) string { switch v := ty.(type) { case spec.PrimitiveType: return v.RawName case spec.DefineStruct: if len(pkg) > 1 { panic("package cannot be more than 1") } if len(pkg) == 0 { return v.RawName } return fmt.Sprintf("%s.%s", pkg[0], strings.Title(v.RawName)) case spec.ArrayType: if len(pkg) > 1 { panic("package cannot be more than 1") } if len(pkg) == 0 { return v.RawName } return fmt.Sprintf("[]%s", golangExpr(v.Value, pkg...)) case spec.MapType: if len(pkg) > 1 { panic("package cannot be more than 1") } if len(pkg) == 0 { return v.RawName } return fmt.Sprintf("map[%s]%s", v.Key, golangExpr(v.Value, pkg...)) case spec.PointerType: if len(pkg) > 1 { panic("package cannot be more than 1") } if len(pkg) == 0 { return v.RawName } return fmt.Sprintf("*%s", golangExpr(v.Type, pkg...)) case spec.InterfaceType: return v.RawName } return "" } func getDoc(doc string) string { if len(doc) == 0 { return "" } return "// " + strings.Trim(doc, "\"") }
go
MIT
8e7e5695eb2095917864b5d6615dab4c90bde3ac
2026-01-07T08:36:18.042207Z
false