MCPcopy
hub / github.com/kingwrcy/moments / GetDoubanBookInfo

Method GetDoubanBookInfo

backend/handler/memo.go:727–838  ·  view source on GitHub ↗

GetDoubanBookInfo godoc @Tags Memo @Summary 获取豆瓣读书详情 @Accept json @Produce json @Param id query int true "豆瓣读书ID" @Param x-api-token header string true "登录TOKEN" @Success 200 {object} vo.DoubanBook @Router /api/memo/

(c echo.Context)

Source from the content-addressed store, hash-verified

725// @Success 200 {object} vo.DoubanBook
726// @Router /api/memo/getDoubanBookInfo [post]
727func (m MemoHandler) GetDoubanBookInfo(c echo.Context) error {
728
729 var (
730 book vo.DoubanBook
731 sysConfigVo vo.FullSysConfigVO
732 sysConfig db.SysConfig
733 re = regexp.MustCompile(`\d{4}-\d{1,2}(-\d{1,2})?`)
734 userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
735 )
736 if err := m.base.db.First(&sysConfig).Error; errors.Is(err, gorm.ErrRecordNotFound) {
737 return FailRespWithMsg(c, Fail, "系统配置为空")
738 }
739 err := json.Unmarshal([]byte(sysConfig.Content), &sysConfigVo)
740 if err != nil {
741 return FailRespWithMsg(c, Fail, "读取系统配置异常")
742 }
743
744 id := c.QueryParam("id")
745 m.base.log.Info().Msgf("开始分析豆瓣图书,id:%s", id)
746
747 target := fmt.Sprintf("https://book.douban.com/subject/%s/", id)
748 // Request the HTML page.
749 client := &http.Client{}
750 start := time.Now()
751 req, _ := http.NewRequest("GET", target, nil)
752 m.base.log.Info().Msgf("请求豆瓣读书地址:%s,耗时:%f秒", target, time.Since(start).Seconds())
753 req.Header.Set("User-Agent", userAgent)
754 res, err := client.Do(req)
755 if err != nil {
756 m.base.log.Error().Msgf("获取豆瓣读书异常:%s", err.Error())
757 return FailRespWithMsg(c, Fail, err.Error())
758 }
759 defer res.Body.Close()
760 if res.StatusCode != 200 {
761 m.base.log.Error().Msgf("豆瓣读书API返回码不是200,而是:%d", res.StatusCode)
762 return FailRespWithMsg(c, Fail, fmt.Sprintf("豆瓣读书API返回码不是200,而是:%d,URL:%s", res.StatusCode, target))
763 }
764
765 // Load the HTML document
766 doc, err := goquery.NewDocumentFromReader(res.Body)
767 if err != nil {
768 m.base.log.Error().Msgf("初始化html错误,%s", err.Error())
769 return FailRespWithMsg(c, Fail, fmt.Sprintf("初始化html错误,%s", err.Error()))
770 }
771
772 doc.Find("meta[property]").Each(func(i int, s *goquery.Selection) {
773 if properties, exists := s.Attr("property"); exists {
774 value := s.AttrOr("content", "")
775 if properties == "og:title" {
776 book.Title = value
777 } else if properties == "og:description" {
778 book.Desc = value
779 } else if properties == "og:image" {
780 book.Image = value
781 } else if properties == "book:author" {
782 book.Author = value
783 } else if properties == "book:isbn" {
784 book.Isbn = value

Callers

nothing calls this directly

Calls 5

FailRespWithMsgFunction · 0.85
downloadImageFunction · 0.85
SuccessRespFunction · 0.85
InfoMethod · 0.80
ErrorMethod · 0.80

Tested by

no test coverage detected