util.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. )
  10. func CheckError(err error) {
  11. if err != nil {
  12. panic(err)
  13. }
  14. }
  15. func Get(url string) (body string, err error) {
  16. if url == "" {
  17. err = errors.New("url is empty\n" + url)
  18. return
  19. }
  20. req, err := http.NewRequest("GET", url, nil)
  21. if err != nil {
  22. return "", err
  23. }
  24. req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
  25. fmt.Println("url:", url)
  26. resp, err := http.DefaultClient.Do(req)
  27. if err != nil {
  28. msg := "this site is not available\n" + url
  29. if err != nil {
  30. msg += "\n" + err.Error()
  31. }
  32. err = errors.New(msg)
  33. return
  34. }
  35. var data []byte
  36. defer resp.Body.Close()
  37. data, err = ioutil.ReadAll(resp.Body)
  38. if err != nil {
  39. return
  40. }
  41. body = string(data)
  42. if resp.StatusCode != 200 {
  43. msg := "this site is not available\n" + url + "\n" + body
  44. err = errors.New(msg)
  45. return
  46. }
  47. return
  48. }
  49. func GetFloat32(s string) float32 {
  50. v, err := strconv.ParseFloat(s, 32)
  51. if err != nil {
  52. v = 0
  53. }
  54. return float32(v)
  55. }
  56. func GetPrice(str string) float32 {
  57. idx := strings.Index(str, "원")
  58. if idx > 0 {
  59. str = str[:idx]
  60. }
  61. str = strings.Replace(str, ",", "", -1)
  62. str = strings.TrimSpace(str)
  63. return GetFloat32(str)
  64. }