Skip to content

Instantly share code, notes, and snippets.

@agusrichard
Created September 18, 2021 15:26
Show Gist options
  • Save agusrichard/0625da55ce59d92599f52024b55d37a7 to your computer and use it in GitHub Desktop.
Save agusrichard/0625da55ce59d92599f52024b55d37a7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"net/http"
"strconv"
"time"
)
func Calculate(x, y int64) int64 {
// get random integer between 0 and 100
n := rand.Intn(100)
// sleep for a random duration between 0 and 100 milliseconds
time.Sleep(time.Duration(n) * time.Millisecond)
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 int 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 int 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)
fmt.Fprintf(w, "%d", result)
}
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