Skip to content

Instantly share code, notes, and snippets.

@limichange
Created November 3, 2024 05:51
Show Gist options
  • Save limichange/5dae557b2e9dfc8f5f59c1987a87f5c7 to your computer and use it in GitHub Desktop.
Save limichange/5dae557b2e9dfc8f5f59c1987a87f5c7 to your computer and use it in GitHub Desktop.
package main
import (
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/gocolly/colly/v2"
)
// MetaInfo 用于存储 meta 信息
type MetaInfo struct {
Name string `json:"name,omitempty"`
Content string `json:"content,omitempty"`
}
// getMetaInfo 从指定的 URL 获取 meta 信息
func getMetaInfo(url string) ([]MetaInfo, error) {
c := colly.NewCollector()
var metaInfos []MetaInfo
c.OnHTML("meta", func(e *colly.HTMLElement) {
name := e.Attr("name")
content := e.Attr("content")
if name != "" && content != "" {
metaInfos = append(metaInfos, MetaInfo{
Name: name,
Content: content,
})
}
})
err := c.Visit(url)
if err != nil {
return nil, err
}
return metaInfos, nil
}
func main() {
r := gin.Default()
// 定义路由
r.GET("/get-meta", func(c *gin.Context) {
url := c.Query("url")
if url == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "Missing 'url' parameter"})
return
}
metaInfos, err := getMetaInfo(url)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, metaInfos)
})
// 获取端口号,使用环境变量 PORT,默认为 8080
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
// 启动 HTTP 服务器
r.Run(":" + port)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment