package auth import ( "context" "crypto/tls" "errors" "fmt" "strings" "sync" "time" "gitea.loveuer.com/loveuer/cluster/pkg/resp" "github.com/go-resty/resty/v2" "github.com/gofiber/fiber/v3" ) func Wallpaper(ctx context.Context) fiber.Handler { type Result struct { Images []struct { Startdate string `json:"startdate"` Fullstartdate string `json:"fullstartdate"` Enddate string `json:"enddate"` URL string `json:"url"` Urlbase string `json:"urlbase"` Copyright string `json:"copyright"` Copyrightlink string `json:"copyrightlink"` Title string `json:"title"` Quiz string `json:"quiz"` Wp bool `json:"wp"` Hsh string `json:"hsh"` Drk int `json:"drk"` Top int `json:"top"` Bot int `json:"bot"` } `json:"images"` } type Store struct { sync.Mutex Date string `json:"date"` Body []byte `json:"body"` Headers map[string]string `json:"headers"` } client := resty.New().SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) apiUrl := "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1" imgUrlPrefix := "https://cn.bing.com" store := &Store{} get := func() ([]byte, map[string]string, error) { var ( err error rr *resty.Response result = new(Result) headers = make(map[string]string) date = time.Now().Format("2006-01-02") ) if store.Date == date { return store.Body, store.Headers, nil } if _, err = client.R(). SetResult(result). Get(apiUrl); err != nil { return nil, nil, fmt.Errorf("[BingWallpaper] get %s err: %w", apiUrl, err) } if len(result.Images) == 0 { err = errors.New("[BingWallpaper]: image length = 0") return nil, nil, err } address := fmt.Sprintf("%s%s", imgUrlPrefix, result.Images[0].URL) if rr, err = client.R(). Get(address); err != nil { err = fmt.Errorf("[BingWallpaper] get image body: %s err: %w", address, err) return nil, nil, err } for key := range rr.Header() { headers[key] = strings.Join(rr.Header()[key], ", ") } store.Lock() store.Date = date store.Body = rr.Body() store.Headers = headers store.Unlock() return rr.Body(), headers, nil } return func(c fiber.Ctx) error { bs, headers, err := get() if err != nil { return resp.R500(c, "", nil, err.Error()) } for key := range headers { c.Set(key, headers[key]) } _, err = c.Write(bs) return err } }