Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Go example more consistent with other examples #619

Merged
merged 1 commit into from
Jun 14, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 26 additions & 52 deletions getting-started-guides/go/fibonacci.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package main

import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"

Expand All @@ -17,10 +17,7 @@ import (
)

const (
name = "getting-started-go"
INPUT_COULD_NOT_BE_PARSED = "Input could not be parsed."
INPUT_IS_OUTSIDE_OF_RANGE = "Input is outside of the range [1,90]."
CALCULATION_SUCCEEDED = "Fibonacci is calculated successfully."
name = "fibonacci-calculator"
)

var (
Expand All @@ -30,10 +27,10 @@ var (
fibonacciInvocations metric.Int64Counter
)

type responseObject struct {
Message string `json:"message"`
Input *int64 `json:"input"`
Output *int64 `json:"output"`
type fibonacciResponse struct {
N int `json:"n,omitempty"`
Result int `json:"result,omitempty"`
Message string `json:"message,omitempty"`
}

func init() {
Expand All @@ -48,57 +45,34 @@ func init() {
}

func fibonacci(w http.ResponseWriter, r *http.Request) {
// Parse input number
num, err := parseNum(r)
n, err := parseNum(r)
if err != nil {
createHttpResponse(
w,
http.StatusBadRequest,
&responseObject{
Message: INPUT_COULD_NOT_BE_PARSED,
Input: &num,
Output: nil,
})
createHttpResponse(w, http.StatusBadRequest, fibonacciResponse{Message: err.Error()})
return
}

// Calculate Fibonacci
out, err := calculateFibonacci(r, num)
result, err := calculateFibonacci(r.Context(), n)
if err != nil {
createHttpResponse(
w,
http.StatusBadRequest,
&responseObject{
Message: INPUT_IS_OUTSIDE_OF_RANGE,
Input: &num,
Output: nil,
})
createHttpResponse(w, http.StatusBadRequest, fibonacciResponse{Message: err.Error()})
return
}

createHttpResponse(
w,
http.StatusOK,
&responseObject{
Message: CALCULATION_SUCCEEDED,
Input: &num,
Output: &out,
})
createHttpResponse(w, http.StatusOK, fibonacciResponse{N: n, Result: result})
}

func parseNum(r *http.Request) (int64, error) {
num, err := strconv.ParseInt(r.URL.Query().Get("n"), 10, 64)
func parseNum(r *http.Request) (int, error) {
n, err := strconv.ParseInt(r.URL.Query().Get("n"), 10, 32)
if err != nil {
log.Print(err.Error())
logger.Error(err.Error())
}
return num, err
return int(n), err
}

func calculateFibonacci(r *http.Request, n int64) (int64, error) {
ctx, span := tracer.Start(r.Context(), "fibonacci")
func calculateFibonacci(ctx context.Context, n int) (int, error) {
ctx, span := tracer.Start(ctx, "fibonacci")
defer span.End()

span.SetAttributes(attribute.Int64("fibonacci.n", n))
span.SetAttributes(attribute.Int("fibonacci.n", n))

if n < 1 || n > 90 {
err := errors.New("n must be between 1 and 90")
Expand All @@ -110,27 +84,27 @@ func calculateFibonacci(r *http.Request, n int64) (int64, error) {
return 0, err
}

var result = int64(1)
var result = 1
if n > 2 {
var a = int64(0)
var b = int64(1)
var a = 0
var b = 1

for i := int64(1); i < n; i++ {
for i := 1; i < n; i++ {
result = a + b
a = b
b = result
}
}

span.SetAttributes(attribute.Int64("fibonacci.result", result))
span.SetAttributes(attribute.Int("fibonacci.result", result))
fibonacciInvocations.Add(ctx, 1, metric.WithAttributes(attribute.Bool("fibonacci.valid.n", true)))
msg := fmt.Sprintf("Computed fib(%d) = %d.", n, result)
logger.InfoContext(ctx, msg, "fibonacci.n", n, "fibonacci.result", result)
return result, nil
}

func createHttpResponse(w http.ResponseWriter, statusCode int, res *responseObject) {
func createHttpResponse(w http.ResponseWriter, statusCode int, res fibonacciResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
payload, _ := json.Marshal(res)
w.Write(payload)
json.NewEncoder(w).Encode(res)
}
Loading