Go语言不需要额外安装依赖,直接使用标准库即可。
package main import ( "encoding/json" "fmt" "net/http" "strings" "golang.org/x/net/html" ) type TDK struct { Title string `json:"title"` Description string `json:"description"` Keywords string `json:"keywords"` } func getTDK(url string) (TDK, error) { resp, err := http.Get(url) if err != nil { return TDK{}, err } defer resp.Body.Close() doc, err := html.Parse(resp.Body) if err != nil { return TDK{}, err } var title, description, keywords string var f func(*html.Node) f = func(n *html.Node) { if n.Type == html.ElementNode && n.Data == "title" { title = n.FirstChild.Data } if n.Type == html.ElementNode && n.Data == "meta" { if getAttr(n, "name") == "description" { description = getAttr(n, "content") } if getAttr(n, "name") == "keywords" { keywords = getAttr(n, "content") } } for c := n.FirstChild; c != nil; c = c.NextSibling { f(c) } } f(doc) return TDK{Title: title, Description: description, Keywords: keywords}, nil } func getAttr(n *html.Node, key string) string { for _, attr := range n.Attr { if attr.Key == key { return attr.Val } } return "" } func tdkHandler(w http.ResponseWriter, r *http.Request) { url := r.URL.Query().Get("url") if url == "" { http.Error(w, `{"error": "URL parameter is required"}`, http.StatusBadRequest) return } tdk, err := getTDK(url) if err != nil { http.Error(w, fmt.Sprintf(`{"error": "%s"}`, err.Error()), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(tdk) } func main() { http.HandleFunc("/tdk", tdkHandler) fmt.Println("Server is running on http://localhost:8080") http.ListenAndServe(":8080", nil) }
将代码保存为 main.go
,然后运行:
go run main.go
访问以下URL来测试API:
http://localhost:8080/tdk?url=https://example.com