-
-
Save rezroo/da8c7c6169dc61da786e3ede78261854 to your computer and use it in GitHub Desktop.
A simple calculator made with Go
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
FROM golang | |
RUN mkdir /build | |
ADD . /build/ | |
WORKDIR /build | |
ADD . ./ | |
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-w -s" -o gocalc . | |
ENTRYPOINT ["./gocalc"] |
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
FROM golang:onbuild as builder | |
RUN mkdir /build | |
ADD . /build/ | |
WORKDIR /build | |
ADD . ./ | |
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -ldflags="-w -s" -o gocalc . | |
FROM scratch | |
COPY --from=builder /build/gocalc / | |
ENTRYPOINT ["/gocalc"] | |
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 ( | |
"errors" | |
"fmt" | |
"os" | |
"strconv" | |
) | |
func calculate(e []string) (float64, error) { | |
result := 0.0 | |
num1, err := strconv.ParseFloat(e[0], 64) | |
if err != nil { | |
return 0.0, err | |
} | |
num2, err := strconv.ParseFloat(e[2], 64) | |
if err != nil { | |
return 0.0, err | |
} | |
switch e[1] { | |
case "*": | |
result = num1 * num2 | |
case "/": | |
if num2 == 0.0 { | |
return 0.0, errors.New("error: you tried to divide by zero.") | |
} | |
result = num1 / num2 | |
case "+": | |
result = num1 + num2 | |
case "-": | |
result = num1 - num2 | |
default: | |
return 0.0, errors.New("error: don't know how to do that") | |
} | |
return result, nil | |
} | |
func main() { | |
if len(os.Args) != 4 { | |
fmt.Println("error: wrong number of arguments") | |
return | |
} | |
res, err := calculate(os.Args[1:]) | |
if err != nil { | |
fmt.Println(err) | |
} else { | |
fmt.Println(res) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment