Skip to content

Commit

Permalink
fix float32 and float64 type conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
emarcey authored and anjmao committed Jun 12, 2019
1 parent 01a8355 commit 07c7548
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 10 deletions.
5 changes: 5 additions & 0 deletions example/in/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ type EventSubForm struct {
User User

PrimitivePointer *int

SliceInt []int
}

type ArrayOfEventField struct {
Expand Down Expand Up @@ -48,4 +50,7 @@ type EventFieldItem struct {
Text string

Rank int32

FloatField1 float32
FloatField2 float64
}
7 changes: 5 additions & 2 deletions example/out/output.proto
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ syntax = "proto3";
package proto;


message ArrayOfEventField {
message ArrayOfEventField {
repeated EventField eventField = 1;
}

message ArrayOfEventFieldItem {
message ArrayOfEventFieldItem {
repeated EventFieldItem eventFieldItem = 1;
}

Expand All @@ -25,6 +25,8 @@ message EventFieldItem {
string eventFieldItemID = 1;
string text = 2;
int32 rank = 3;
float floatField1 = 4;
double floatField2 = 5;
}

message EventSubForm {
Expand All @@ -34,6 +36,7 @@ message EventSubForm {
ArrayOfEventField fields = 4;
User user = 5;
int64 primitivePointer = 6;
repeated int64 sliceInt = 7;
}

message User {
Expand Down
31 changes: 23 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,22 +144,37 @@ func toProtoFieldTypeName(f *types.Var) string {
case *types.Basic:
name := f.Type().String()
return normalizeType(name)
case *types.Slice, *types.Pointer, *types.Struct:
// TODO: this is ugly. Find another way of getting field type name.
parts := strings.Split(f.Type().String(), ".")
name := parts[len(parts)-1]
if name[0] == '*' {
name = name[1:]
}
case *types.Slice:
name := splitNameHelper(f)
return normalizeType(strings.TrimLeft(name, "[]"))

case *types.Pointer, *types.Struct:
name := splitNameHelper(f)
return normalizeType(name)
}
return f.Type().String()
}

func splitNameHelper(f *types.Var) string {
// TODO: this is ugly. Find another way of getting field type name.
parts := strings.Split(f.Type().String(), ".")

name := parts[len(parts)-1]

if name[0] == '*' {
name = name[1:]
}
return name
}

func normalizeType(name string) string {
switch name {
case "int":
return "int64"
case "float32":
return "float"
case "float64":
return "double"
default:
return name
}
Expand All @@ -185,7 +200,7 @@ package proto;
{{range .}}
message {{.Name}} {
{{- range .Fields}}
{{- if .IsRepeated}}
{{- if .IsRepeated}}
repeated {{.TypeName}} {{.Name}} = {{.Order}};
{{- else}}
{{.TypeName}} {{.Name}} = {{.Order}};
Expand Down

0 comments on commit 07c7548

Please sign in to comment.