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

Respuesta de la IA

En este código, el servidor HTTP siempre devuelve 0 para la solicitud "/car/instant", aunque la función getCarPrice() genera un precio aleatorio con una demora de 1 segundo.

El problema es que el manejador no llama a getCarPrice(), sino que responde inmediatamente con 0, posiblemente para no bloquear el hilo.

Si se desea devolver el precio actual del coche, pero sin bloquear el manejador, se puede usar un enfoque asíncrono, por ejemplo, almacenando en caché el precio en una goroutine separada y devolviendo el último valor instantáneamente.

Ejemplo con caché del precio en segundo plano:

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)
}

De esta forma, el servidor responde rápidamente con el valor más reciente de precio, que se actualiza en segundo plano.