Last active
September 18, 2021 17:24
-
-
Save agusrichard/ddf87075fb363f1c16b1a9574a58376a to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"math/rand" | |
"net/http" | |
"strconv" | |
"time" | |
) | |
func Calculate(x, y int64) int64 { | |
// get random integer between 0 and 2000 | |
n := rand.Intn(2000) | |
// sleep for a random duration between 0 and 2000 milliseconds | |
time.Sleep(time.Duration(n) * time.Millisecond) | |
return x + y | |
} | |
func CalculateSlow(x, y int64) int64 { | |
// sleep for 2 seconds to mock heavy calculation | |
time.Sleep(2 * time.Second) | |
return x + y | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
// Get the query string from the request | |
queryX, queryY := r.URL.Query().Get("x"), r.URL.Query().Get("y") | |
// Parse the input from user to int64 or returns error if it fails | |
x, err := strconv.ParseInt(queryX, 10, 64) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
// Parse the input from user to int64 or returns error if it fails | |
y, err := strconv.ParseInt(queryY, 10, 64) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
result := Calculate(x, y) | |
resultSlow := CalculateSlow(x, y) | |
fmt.Fprintf(w, "%d", result+resultSlow) | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":8080", nil) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment