Advertisement
fenixD3

go recover and deadlock

Aug 8th, 2024
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.36 KB | None | 0 0
  1. package build_cnippet_avito
  2.  
  3. import (
  4.     "fmt"
  5.     "regexp"
  6.     "time"
  7. )
  8.  
  9. // itemDescription симулирует получение описания из сервиса
  10. func itemDescription(itemID int) string {
  11.     time.Sleep(time.Second * 1)
  12.     return "☆☆☆Lorem ♡♡♡ ipsum  dolor sit amet..."
  13. }
  14.  
  15. // itemPrice симулирует получение цены в долларах из сервиса
  16. func itemPrice(itemId int) float64 {
  17.     time.Sleep(2 * time.Second)
  18.     return 100
  19. }
  20.  
  21. func prettify(description string) string {
  22.     time.Sleep(time.Second * 1)
  23.     re := regexp.MustCompile("\\W+")
  24.     panic("Huy")
  25.     return re.ReplaceAllString(description, "")
  26. }
  27.  
  28. func priceToRub(price float64) float64 {
  29.     time.Sleep(1 * time.Second)
  30.     return price * 70
  31. }
  32.  
  33. type Snippet struct {
  34.     Price       float64
  35.     Description string
  36. }
  37.  
  38. func BuildSnippet(itemId int) Snippet {
  39.     // write your code here
  40.     //type descResult struct {
  41.     //    desc string
  42.     //    err error
  43.     //}
  44.  
  45.     descCh := make(chan string)
  46.     go func() {
  47.         defer func() {
  48.             fmt.Println("recovered:", recover())
  49.         }()
  50.         rawDesc := itemDescription(itemId)
  51.         finalDesc := prettify(rawDesc)
  52.         fmt.Println("Here")
  53.         descCh <- finalDesc
  54.         close(descCh)
  55.     }()
  56.  
  57.     rawPrice := itemPrice(itemId)
  58.     finalPrice := priceToRub(rawPrice)
  59.  
  60.     descItem := <-descCh
  61.     return Snippet{Price: finalPrice, Description: descItem}
  62. }
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement