util.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strconv"
  8. )
  9. func CheckError(err error) {
  10. if err != nil {
  11. panic(err)
  12. }
  13. }
  14. func Get(url string) (body string, err error) {
  15. if url == "" {
  16. err = errors.New("url is empty\n" + url)
  17. return
  18. }
  19. req, err := http.NewRequest("GET", url, nil)
  20. if err != nil {
  21. return "", err
  22. }
  23. 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")
  24. fmt.Println("url:", url)
  25. resp, err := http.DefaultClient.Do(req)
  26. if err != nil {
  27. msg := "this site is not available\n" + url
  28. if err != nil {
  29. msg += "\n" + err.Error()
  30. }
  31. err = errors.New(msg)
  32. return
  33. }
  34. var data []byte
  35. defer resp.Body.Close()
  36. data, err = ioutil.ReadAll(resp.Body)
  37. if err != nil {
  38. return
  39. }
  40. body = string(data)
  41. if resp.StatusCode != 200 {
  42. msg := "this site is not available\n" + url + "\n" + body
  43. err = errors.New(msg)
  44. return
  45. }
  46. return
  47. }
  48. func GetFloat32(s string) float32 {
  49. v, err := strconv.ParseFloat(s, 32)
  50. if err != nil {
  51. v = 0
  52. }
  53. return float32(v)
  54. }