ada395a8da105a42505ccd59aa3129442d9f08aa.svn-base 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package service
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "github.com/afex/hystrix-go/hystrix"
  7. "github.com/longjoy/micro-go-course/section24/goods/common"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. )
  12. type GoodsDetailVO struct {
  13. Id string
  14. Name string
  15. Comments common.CommentListVO
  16. }
  17. type Service interface {
  18. GetGoodsDetail(ctx context.Context, id string) (GoodsDetailVO, error)
  19. }
  20. func NewGoodsServiceImpl() Service {
  21. return &GoodsDetailServiceImpl{}
  22. }
  23. type GoodsDetailServiceImpl struct{}
  24. func (service *GoodsDetailServiceImpl) GetGoodsDetail(ctx context.Context, id string) (GoodsDetailVO, error) {
  25. detail := GoodsDetailVO{Id: id, Name: "Name"}
  26. var err error
  27. commonResult, err := GetGoodsComments(id)
  28. detail.Comments = commonResult.Detail
  29. if err != nil {
  30. return detail, err
  31. }
  32. return detail, nil
  33. }
  34. func GetGoodsComments(id string) (common.CommentResult, error) {
  35. var result common.CommentResult
  36. serviceName := "Comments"
  37. err := hystrix.Do(serviceName, func() error {
  38. requestUrl := url.URL{
  39. Scheme: "http",
  40. Host: "127.0.0.1" + ":" + "8081",
  41. Path: "/comments/detail",
  42. RawQuery: "id=" + id,
  43. }
  44. resp, err := http.Get(requestUrl.String())
  45. if err != nil {
  46. return err
  47. }
  48. body, _ := ioutil.ReadAll(resp.Body)
  49. jsonErr := json.Unmarshal(body, &result)
  50. if jsonErr != nil {
  51. return jsonErr
  52. }
  53. return nil
  54. }, func(e error) error {
  55. // 断路器打开时的处理逻辑,本示例是直接返回错误提示
  56. return errors.New("Http errors!")
  57. })
  58. if err == nil {
  59. return result, nil
  60. } else {
  61. return result, err
  62. }
  63. }