Created
August 23, 2017 09:34
-
-
Save egonelbre/f4fb56fe1eb95fe9342e2af545d87177 to your computer and use it in GitHub Desktop.
Go: reflection based generation (https://play.golang.org/p/y5qKxuoV9t)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"time" | |
) | |
type Status struct { | |
APC string | |
Date time.Time | |
Hostname string `key:"HOSTNAME"` | |
Version string `key:"VERSION"` | |
UPSName string `key:"UPS"` | |
Cable string `key:"CABLE"` | |
Driver string `key:"DRIVER"` | |
UPSMode string `key:"UPS"` | |
StartTime time.Time | |
Model string | |
Status string | |
// ... | |
} | |
func Generate(v interface{}) { | |
t := reflect.TypeOf(v) | |
fmt.Println("func (s *" + t.Name() + ") Set(key string, value string) {") | |
defer fmt.Println("}") | |
fmt.Println("\tswitch key {") | |
defer fmt.Println("\t}") | |
for i := 0; i < t.NumField(); i++ { | |
f := t.Field(i) | |
key := f.Tag.Get("key") | |
if key == "" { | |
continue | |
} | |
fmt.Printf("\tcase %q:\n", key) | |
fmt.Println("\t\ts." + f.Name + " = value") | |
} | |
} | |
func main() { | |
Generate(Status{}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment