1package main2 3import (4 "fmt"5 "log"6 "net/http"7 "sync"8 "time"9)10 11func main() {12 prices, err := loadPrices()13 if err != nil {14 log.Fatalf("load initial prices: %s", err)15 }16 17 // фоновое обновление курсов18 go func() {19 for {20 time.Sleep(time.Minute)21 prices, err = loadPrices()22 if err != nil {23 log.Printf("ERR: refresh prices: %s", err)24 }25 prices = newPrices26 }27 }()28 29 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {30 // разобрать 'from' и 'value' из query params31 32 from := "JPY"33 val := 250.034 35 rate, ok := prices[from]36 if !ok {37 http.NotFound(w, r)38 return39 }40 41 result := val / rate42 43 fmt.Fprint(w, result)44 })45 46 if err := http.ListenAndServe(":8080", nil); err != http.ErrServerClosed {47 log.Fatal(err)48 }49}50 51// loadPrices читает курсы из файла или внешнего сервиса (относительно долгая функция).52func loadPrices() (map[string]float64, error) {53 time.Sleep(100 * time.Millisecond)54 55 return map[string]float64{56 "USD": 1.0,57 "JPY": 150.0,58 "EUR": 0.9,59 }, nil60}