Golang 本机网络请求拦截广告和敏感词 - 代码示例及详细注释
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
func main() {
// 创建HTTP服务器
http.HandleFunc("/", handleRequest)
http.ListenAndServe(":8080", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
// 获取请求的URL
url := r.URL.String()
// 检查URL是否包含广告链接
if checkAds(url) {
http.Error(w, "广告链接被拦截", http.StatusForbidden)
return
}
// 检查请求的内容是否包含敏感字词
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "请求内容读取失败", http.StatusInternalServerError)
return
}
defer r.Body.Close()
if checkSensitiveWords(string(body)) {
http.Error(w, "请求内容含有敏感字词", http.StatusForbidden)
return
}
// 处理正常的请求
fmt.Fprintf(w, "请求已被允许")
}
func checkAds(url string) bool {
// 此处可以根据实际需求添加更多的广告链接匹配规则
adsRegex := regexp.MustCompile(ad|ads|advertisement|banner)
return adsRegex.MatchString(url)
}
func checkSensitiveWords(content string) bool {
// 此处可以根据实际需求添加更多的敏感字词匹配规则
sensitiveWords := []string{"敏感词1", "敏感词2", "敏感词3"}
for _, word := range sensitiveWords {
if strings.Contains(content, word) {
return true
}
}
return false
}
原文地址: https://www.cveoy.top/t/topic/pnFB 著作权归作者所有。请勿转载和采集!