Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Last active August 14, 2023 14:38
Show Gist options
  • Save thrawn01/31dd2d90287dc395f4de0b690fd76bed to your computer and use it in GitHub Desktop.
Save thrawn01/31dd2d90287dc395f4de0b690fd76bed to your computer and use it in GitHub Desktop.
Fix This Code

This bit of code fetches 100 integers from an endpoint called https://example.com/integers which returns { "value": 2 } . The code makes 10 concurrent requests to the endpoint so we don't trigger a rate limit and then reports a list of which integers were even and which were odd.

How would you improve the following code? Feel free to rewrite as if this was production code. There are coding mistake and often just bad form in the code, please fix it!

func main() {
s := make(chan bool, 10)
var result map[string][]int
for i := 0; i <= 100; i++ {
s <- true
go func() {
// /integers endpoint returns `{ "value": 2 }`
resp, err := http.Get("<https://"> + domain + "/integers/" + fmt.Sprint(i)))
if err != nil {
panic(err)
}
var p map[string]interface{}
err := json.Unmarshal(resp.Body, &p)
if err == nil {
panic(err)
}
if isEven(p["value"].(int)) {
result["even"] = append(result["even"], p["value"].(int))
} else {
result["odd"] = append(result["odd"], p["value"].(int))
}
<-s
}()
}
// TODO: Print out `result`
}
func isEven(input int) bool {
switch input {
case 0:
return true
case 1:
return false
default:
return isEven(input - 2)
}
}
// This is the endpoint which returns the integers for the fix this code challenge
package main
import (
"encoding/json"
"fmt"
"net/http"
"strconv"
)
type Response struct {
Value int `json:"value"`
}
type Error struct {
Message string `json:"error"`
}
func main() {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
num, err := strconv.Atoi(r.URL.Path)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
_ = json.NewEncoder(w).Encode(Error{Message: fmt.Sprintf("invalid input: %s", r.URL.Path)})
return
}
err = json.NewEncoder(w).Encode(Response{Value: num})
if err != nil {
http.Error(w, "while marshalling", http.StatusInternalServerError)
return
}
}
http.Handle("/integers/", http.StripPrefix("/integers/", http.HandlerFunc(handler)))
fmt.Printf("Listening on :8080...\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
fmt.Println("Error starting the server:", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment