go-examples/converter/main.go
2017-07-07 14:29:36 +02:00

77 lines
1.5 KiB
Go

package main
import "fmt"
import "log"
import "os"
import "strconv"
import "strings"
const (
markerMiles = "mi"
markerKm = "km"
markerFeet = "ft"
markerMeter = "m"
MilesToKm float64 = 1.609344
FeetsToMeters float64 = 3.28084
)
var (
inUnit string
inVal float64
asMeter float64
err error
convVal float64
)
func main() {
if len(os.Args) < 3 {
log.Fatalln("Needs 2 arguments")
}
input := os.Args[1]
convTo := os.Args[2]
switch {
case strings.HasSuffix(input, markerKm):
inUnit = markerKm
case strings.HasSuffix(input, markerFeet):
inUnit = markerFeet
case strings.HasSuffix(input, markerMeter):
inUnit = markerMeter
case strings.HasSuffix(input, markerMiles):
inUnit = markerMiles
default:
log.Fatalln("Invalid input:", input)
}
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
if err != nil {
log.Fatalln("Invalid input number", err)
}
switch inUnit {
case markerMiles:
asMeter = inVal * MilesToKm * 1000
case markerKm:
asMeter = inVal * 1000
case markerFeet:
asMeter = inVal * FeetsToMeters
case markerMeter:
asMeter = inVal
}
// fmt.Println(inVal, inUnit, asMeter, convTo)
switch convTo {
case markerMiles:
convVal = asMeter / (MilesToKm * 1000)
case markerKm:
convVal = asMeter / 1000
case markerFeet:
convVal = asMeter / FeetsToMeters
case markerMeter:
convVal = asMeter
default:
log.Fatalln("Invalid unit: " + convTo)
}
fmt.Printf("%.2f%s\n", convVal, convTo)
}