Go 语言图像请求

与自有程序集成页面希望增加 Golang 语言的案例,来自
@okatu-loli ,Go 实现 Cravatar 示例如下,可供参考。

package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"net/url"
	"strings"
)

// GetCravatar 返回指定电子邮件地址的 Cravatar URL 或完整的图像标签
func GetCravatar(email string, size int, defaultImage, rating string, imgTag bool, attrs map[string]string) string {
	// 构建基本的 Cravatar URL
	baseURL := "https://cravatar.cn/avatar/"
	
	// 清理并对电子邮件地址进行 MD5 哈希处理
	email = strings.TrimSpace(strings.ToLower(email))
	hash := md5.New()
	hash.Write([]byte(email))
	emailHash := hex.EncodeToString(hash.Sum(nil))
	
	// 构建 Cravatar URL
	cravURL := fmt.Sprintf("%s%s?s=%d&d=%s&r=%s", baseURL, emailHash, size, defaultImage, rating)
	
	// 如果 imgTag 为 true,则返回完整的 <img> 标签
	if imgTag {
		imgTagStr := fmt.Sprintf(`<img src="%s"`, cravURL)
		for key, value := range attrs {
			imgTagStr += fmt.Sprintf(` %s="%s"`, key, value)
		}
		imgTagStr += " />"
		return imgTagStr
	}
	
	// 否则,仅返回 URL
	return cravURL
}

func main() {
	email := "someone@somewhere.com"
	size := 40
	defaultImage := "https://www.somewhere.com/homestar.jpg"
	rating := "g"
	imgTag := true
	attrs := map[string]string{"class": "avatar", "alt": "User Avatar"}

	// 获取 Cravatar 图像 URL 或 img 标签
	result := GetCravatar(email, size, defaultImage, rating, imgTag, attrs)
	fmt.Println(result)
}

论坛原贴:https://cravatar.com/forums/topic/24944/

文档最后修改于

文派文库团队编撰