Sobes.tech
Principal

func getCarPrice() int64 { time.Sleep(1 * time.Second) return rand.Int63n(1000) } func main() { http.HandleFunc("/car/instant", func(resp http.ResponseWriter, req *http.Request) { fmt.Fprintf(resp, "%d", 0) }) http.ListenAndServe(":8080", nil) }

sobes.tech AI

Answer from AI

In this code, the HTTP server always returns 0 for the request "/car/instant", even though the getCarPrice() function generates a random price with a 1-second delay.

The problem is that the handler does not call getCarPrice(), but immediately responds with 0, possibly to avoid blocking the thread.

If you want to return the actual car price without blocking the handler, you can use an asynchronous approach, such as caching the price in a separate goroutine and returning the last value instantly.

Example with background price caching:

package main

import (
    "fmt"
    "math/rand"
    "net/http"
    "sync/atomic"
    "time"
)

var carPrice int64

func updateCarPrice() {
    for {
        time.Sleep(1 * time.Second)
        price := rand.Int63n(1000)
        atomic.StoreInt64(&carPrice, price)
    }
}

func main() {
    go updateCarPrice()

    http.HandleFunc("/car/instant", func(resp http.ResponseWriter, req *http.Request) {
        price := atomic.LoadInt64(&carPrice)
        fmt.Fprintf(resp, "%d", price)
    })

    http.ListenAndServe(":8080", nil)
}

This way, the server always responds quickly with the last known price, which is updated in the background.

func getCarPrice() int64 { time.Sleep(1 *… - sobes.tech