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




B2C电商系统商城源码支持pC+小程序+公众号+H5可打包App源...
原生开发淘宝客App,Android+ios独立开发,全开源支持二...
知识付费系统在线教育平台源码+题库系统源码,PC+公众号商业授权...
B2C单商户电商系统源码部署小程序+公众号+H5+App源码...
教育知识付费系统源码带题库功能商业授权公众号+H5源码...