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
პასუხი AI-სგან
ამ კოდში, HTTP-სერვერი ყოველთვის აბრუნებს 0- ს მოთხოვნისთვის "/car/instant", მაშინაც კი, როდესაც getCarPrice() ფუნქცია გენერირებს შემთხვევით ფასს 1 წამით დაგვიანებით.
პრობლემა ის არის, რომ handler-ი არ იძახის getCarPrice()-ს, არამედ დაუყოვნებლივ პასუხობს 0- ს, ალბათ, რომ არ ბლოკავდეს ნაკადს.
თუ გსურთ რეალური მანქანის ფასის დაბრუნება, მაგრამ handler-ი არ ბლოკოს, შეგიძლიათ გამოიყენოთ ასინქრონული მიდგომა, მაგალითად, ფასის კეშირება ცალკე goroutine-ში და ბოლო მნიშვნელობის დაუყოვნებლივ დაბრუნება.
ფონის ფასის კეშირების მაგალითი:
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)
}
ამ გზით, სერვერი სწრაფად პასუხობს ბოლო ცნობილ ფასს, რომელიც ფონზე განახლდება.