コード例 #1
0
ファイル: gravatar2qiniu.go プロジェクト: hjqhezgh/gopher
func main() {
	ACCESS_KEY = gopher.Config.QiniuAccessKey
	SECRET_KEY = gopher.Config.QiniuSecretKey

	extra := &qiniu_io.PutExtra{
		Bucket:         "gopher",
		MimeType:       "",
		CustomMeta:     "",
		CallbackParams: "",
	}

	var policy = rs.PutPolicy{
		Scope: "gopher",
	}

	c := gopher.DB.C("users")
	var users []gopher.User
	c.Find(nil).All(&users)

	for _, user := range users {
		url := webhelpers.Gravatar(user.Email, 256)
		resp, err := http.Get(url)
		if err != nil {
			fmt.Println("get gravatar image error:", url, err.Error())
			return
		}

		filename := strings.Replace(uuid.NewUUID().String(), "-", "", -1) + ".jpg"
		body, _ := ioutil.ReadAll(resp.Body)

		h := md5.New()
		h.Write(body)
		md5Str := fmt.Sprintf("%x", h.Sum(nil))

		if md5Str != "ac83818c6d5b6aca4b6f796b6d3cb338" {
			// 不是默认头像,上传
			key := "avatar/" + filename
			ret := new(qiniu_io.PutRet)

			buf := bytes.NewBuffer(body)

			err = qiniu_io.Put(nil, ret, policy.Token(), key, buf, extra)
			if err == nil {
				c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}})
				fmt.Printf("upload %s's avatar success: %s\n", user.Email, filename)
			} else {
				fmt.Printf("upload %s' avatar error: %s\n", user.Email, err.Error())
			}
		}

		resp.Body.Close()
	}
}
コード例 #2
0
ファイル: user_center.go プロジェクト: ZuiGuangYin/gopher
// URl: /user_center/get_gravatar
// 从 Gravatar 获取头像
func setAvatarFromGravatar(handler *Handler) {
	user, _ := currentUser(handler)
	url := webhelpers.Gravatar(user.Email, 256)
	resp, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	filename, err := uploadAvatarToQiniu(resp.Body, resp.Header["Content-Type"][0])
	if err != nil {
		panic(err)
	}

	c := handler.DB.C(USERS)
	c.Update(bson.M{"_id": user.Id_}, bson.M{"$set": bson.M{"avatar": filename}})

	http.Redirect(handler.ResponseWriter, handler.Request, "/profile#avatar", http.StatusFound)
}