@@ -0,0 +1,16 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"videoweb/pub/common/useragent"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// applyClientForwardHeaders 向上游透传客户端 IP / UA(与 API 上游一致):
|
||||
// X-Real-IP、User-Agent、X-User-Agent。
|
||||
func applyClientForwardHeaders(header map[string]string, c *gin.Context) {
|
||||
if header == nil {
|
||||
return
|
||||
}
|
||||
useragent.ApplyToHeader(header, c, useragent.DefaultVer)
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"videoweb/app/api/web"
|
||||
"videoweb/app/appg"
|
||||
"videoweb/app/service/commentser"
|
||||
"videoweb/app/service/playletser"
|
||||
"videoweb/app/service/seoser"
|
||||
"videoweb/app/service/translationser"
|
||||
"videoweb/app/service/videoser"
|
||||
staticassets "videoweb/app/static"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// Init 初始化 Gin,注册静态资源与业务路由。
|
||||
func Init() *gin.Engine {
|
||||
setGinMode()
|
||||
engine := gin.Default()
|
||||
engine.HandleMethodNotAllowed = true
|
||||
setupEngine(engine)
|
||||
registerM3U8Routes(engine)
|
||||
registerSitemapRoutes(engine)
|
||||
registerRoutes(engine)
|
||||
engine.NoMethod(web.NotFound)
|
||||
return engine
|
||||
}
|
||||
|
||||
// DHInit 导航站独立端口:仅暴露官方导航页及静态资源。
|
||||
func DHInit() *gin.Engine {
|
||||
setGinMode()
|
||||
engine := gin.Default()
|
||||
engine.HandleMethodNotAllowed = true
|
||||
setupEngine(engine)
|
||||
engine.GET("/", web.Nav)
|
||||
engine.GET("/nav/", web.Nav)
|
||||
engine.GET("/dh/", web.Nav)
|
||||
engine.NoRoute(web.NotFound)
|
||||
engine.NoMethod(web.NotFound)
|
||||
return engine
|
||||
}
|
||||
|
||||
func setGinMode() {
|
||||
mode := strings.ToLower(strings.TrimSpace(appg.Conf.RunMod))
|
||||
if envMode := strings.ToLower(strings.TrimSpace(os.Getenv(gin.EnvGinMode))); envMode != "" {
|
||||
mode = envMode
|
||||
}
|
||||
switch mode {
|
||||
case "test":
|
||||
gin.SetMode(gin.TestMode)
|
||||
case "prod", "production", "release":
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
default:
|
||||
gin.SetMode(gin.DebugMode)
|
||||
}
|
||||
}
|
||||
|
||||
func setupEngine(engine *gin.Engine) {
|
||||
tplFuncs := playletser.TemplateFuncs()
|
||||
for name, fn := range commentser.TemplateFuncs() {
|
||||
tplFuncs[name] = fn
|
||||
}
|
||||
tplFuncs["InJSONScript"] = inJSONScript
|
||||
tplFuncs["navHref"] = translationser.NavHref
|
||||
tplFuncs["navIsDownload"] = translationser.NavIsDownload
|
||||
tplFuncs["navIsActive"] = translationser.NavIsActive
|
||||
tplFuncs["navDrawerIcon"] = translationser.NavDrawerIcon
|
||||
tplFuncs["navHasMegaMenu"] = translationser.NavHasMegaMenu
|
||||
tplFuncs["listThemeSegment"] = translationser.ListThemeSegmentFromPath
|
||||
tplFuncs["listUpdateStatus"] = translationser.ListUpdateStatusFromPath
|
||||
tplFuncs["seriesListURL"] = videoser.SeriesListURL
|
||||
tplFuncs["videoDetailURL"] = videoser.VideoDetailURL
|
||||
tplFuncs["videoPlayURL"] = videoser.VideoPlayURL
|
||||
tplFuncs["mediaTypeLabel"] = videoser.MediaTypeLabel
|
||||
tplFuncs["episodeLabel"] = videoser.EpisodeLabel
|
||||
engine.SetFuncMap(tplFuncs)
|
||||
engine.SetHTMLTemplate(mustHTMLTemplate(tplFuncs))
|
||||
engine.Use(strictTransportSecurity(), staticCacheHeaders(), crawlerHeaders())
|
||||
engine.StaticFS("/static", http.FS(staticassets.FS))
|
||||
}
|
||||
|
||||
// strictTransportSecurity 仅在请求实际通过 HTTPS 到达,或可信代理标记首个协议为 HTTPS 时启用 HSTS。
|
||||
// 不声明 includeSubDomains/preload,避免把尚未确认支持 HTTPS 的子域一并纳入。
|
||||
func strictTransportSecurity() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if isHTTPSRequest(c.Request) {
|
||||
c.Header("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func isHTTPSRequest(r *http.Request) bool {
|
||||
if r == nil {
|
||||
return false
|
||||
}
|
||||
if r.TLS != nil {
|
||||
return true
|
||||
}
|
||||
proto := r.Header.Get("X-Forwarded-Proto")
|
||||
if i := strings.IndexByte(proto, ','); i >= 0 {
|
||||
proto = proto[:i]
|
||||
}
|
||||
return strings.EqualFold(strings.TrimSpace(proto), "https")
|
||||
}
|
||||
|
||||
// crawlerHeaders 防止接口和媒体工具响应进入搜索索引。
|
||||
func crawlerHeaders() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
path := c.Request.URL.Path
|
||||
if strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/h5/") ||
|
||||
path == "/enkey" || path == "/newenkey" || path == "/healthz" {
|
||||
c.Header("X-Robots-Tag", "noindex, nofollow")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// inJSONScript 将任意数据序列化为可嵌入 <script> 的 JSON。
|
||||
func inJSONScript(v any) template.JS {
|
||||
b, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
return template.JS("null")
|
||||
}
|
||||
return template.JS(b)
|
||||
}
|
||||
|
||||
// staticCacheHeaders 为静态资源设置浏览器缓存。
|
||||
func staticCacheHeaders() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if strings.HasPrefix(c.Request.URL.Path, "/static/") {
|
||||
c.Header("Cache-Control", "public, max-age=604800, stale-while-revalidate=86400")
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func registerRoutes(r *gin.Engine) {
|
||||
// 页面路由与 template/pages 文件名对应:camelCase → kebab-case(如 popularRecommend → /popular-recommend)
|
||||
r.GET("/", web.Index)
|
||||
r.GET("/search-mobile", web.SearchMobile)
|
||||
r.GET("/search", web.Search)
|
||||
r.GET("/search/:q", web.Search)
|
||||
r.GET("/search/:q/page/:page", web.Search)
|
||||
r.GET("/profile", web.Profile)
|
||||
r.GET("/history", web.History)
|
||||
r.GET("/history/page/:page", web.History)
|
||||
r.POST("/api/playlet/history/clear", web.HistoryClear)
|
||||
r.POST("/api/playlet/history/delete", web.HistoryDelete)
|
||||
r.POST("/api/video/history/clear", web.VideoHistoryClear)
|
||||
r.POST("/api/video/history/delete", web.VideoHistoryDelete)
|
||||
r.GET("/favorites", web.Favorites)
|
||||
r.GET("/favorites/page/:page", web.Favorites)
|
||||
r.GET("/favorites/:filter", web.Favorites)
|
||||
r.GET("/favorites/:filter/page/:page", web.Favorites)
|
||||
r.GET("/purchased", web.PurchasedSeries)
|
||||
r.GET("/purchased/page/:page", web.PurchasedSeries)
|
||||
r.GET("/setting", web.Setting)
|
||||
r.GET("/settings", func(c *gin.Context) {
|
||||
c.Redirect(http.StatusMovedPermanently, "/setting")
|
||||
})
|
||||
r.GET("/recharge", web.Recharge)
|
||||
r.GET("/about", web.About)
|
||||
r.GET("/help", web.Help)
|
||||
r.GET("/terms", web.Terms)
|
||||
r.GET("/privacy", web.Privacy)
|
||||
r.GET("/2257", web.Compliance2257)
|
||||
r.GET("/dmca", web.DMCA)
|
||||
r.GET("/download-app", web.DownloadApp)
|
||||
r.GET("/nav", web.Nav)
|
||||
r.GET("/nav/", web.Nav)
|
||||
r.GET("/dh", web.Nav)
|
||||
r.GET("/dh/", web.Nav)
|
||||
r.GET("/list", web.List)
|
||||
r.GET("/list/:theme", web.List)
|
||||
r.GET("/list/:theme/:updateStatus/:sortType", web.List)
|
||||
r.GET("/list/:theme/:updateStatus/:sortType/page/:page", web.List)
|
||||
r.GET("/more-list/:configId/:timeRange/:theme/page/:page", web.MoreList)
|
||||
r.GET("/more-list/:configId/:timeRange/:theme", web.MoreList)
|
||||
r.GET("/more-list/:configId/page/:page", web.MoreList)
|
||||
r.GET("/more-list/:configId", web.MoreList)
|
||||
r.GET("/more-series-list/:configId/:timeRange/:theme/page/:page", web.MoreSeriesList)
|
||||
r.GET("/more-series-list/:configId/:timeRange/:theme", web.MoreSeriesList)
|
||||
r.GET("/more-series-list/:configId/page/:page", web.MoreSeriesList)
|
||||
r.GET("/more-series-list/:configId", web.MoreSeriesList)
|
||||
r.GET("/series", web.Series)
|
||||
r.GET("/series/:media/:topic/:sortType", web.Series)
|
||||
r.GET("/series/:media/:topic/:sortType/page/:page", web.Series)
|
||||
r.GET("/topic", web.Topic)
|
||||
r.GET("/topic/page/:page", web.Topic)
|
||||
r.GET("/topic/sort/:sortType", web.Topic)
|
||||
r.GET("/topic/sort/:sortType/page/:page", web.Topic)
|
||||
r.GET("/topic-detail/:slug/sort/:sortType/page/:page", web.TopicDetail)
|
||||
r.GET("/topic-detail/:slug/sort/:sortType", web.TopicDetail)
|
||||
r.GET("/topic-detail/:slug/page/:page", web.TopicDetail)
|
||||
r.GET("/topic-detail/:slug", web.TopicDetail)
|
||||
r.GET("/rank", web.Rank)
|
||||
r.GET("/rank/page/:page", web.Rank)
|
||||
r.GET("/rank/:sortOrder", web.Rank)
|
||||
r.GET("/rank/:sortOrder/page/:page", web.Rank)
|
||||
r.GET("/tags/:slug/sort/:sortType/page/:page", web.Tags)
|
||||
r.GET("/tags/:slug/sort/:sortType", web.Tags)
|
||||
r.GET("/tags/:slug/page/:page", web.Tags)
|
||||
r.GET("/tags/:slug", web.Tags)
|
||||
r.GET("/recently-added", web.RecentlyAdded)
|
||||
r.GET("/recently-added/page/:page", web.RecentlyAdded)
|
||||
r.GET("/popular-recommend", web.PopularRecommend)
|
||||
r.GET("/popular-recommend/page/:page", web.PopularRecommend)
|
||||
r.GET("/popular-recommend/:rankType", web.PopularRecommend)
|
||||
r.GET("/popular-recommend/:rankType/page/:page", web.PopularRecommend)
|
||||
r.GET("/play/:slug", web.Play)
|
||||
r.GET("/play/:slug/:ep", web.Play)
|
||||
r.GET("/play/:slug/recommendations/page/:guessPage", web.Play)
|
||||
r.GET("/play/:slug/:ep/recommendations/page/:guessPage", web.Play)
|
||||
r.GET("/series-play/:slug", web.SeriesPlay)
|
||||
r.GET("/series-play/:slug/recommendations/page/:guessPage", web.SeriesPlay)
|
||||
r.GET("/login", web.LoginPage)
|
||||
r.GET("/register", web.RegisterPage)
|
||||
r.GET("/feedback", web.Feedback)
|
||||
|
||||
// 认证 BFF:SSR 进页已自动游客;前端登录/注册/补游客会话走以下接口。
|
||||
r.POST("/api/auth/guest", web.Guest)
|
||||
r.POST("/api/auth/login", web.Login)
|
||||
r.POST("/api/auth/register", web.Register)
|
||||
r.POST("/api/auth/logout", web.Logout)
|
||||
r.POST("/api/auth/profile", web.UpdateProfile)
|
||||
r.POST("/api/recharge/coin/buy", web.RechargeCoinBuy)
|
||||
r.POST("/api/coin/buy", web.RechargeCoinBuy)
|
||||
r.GET("/api/recharge/transactions", web.RechargeTransactions)
|
||||
r.GET("/api/coin/trans/list", web.RechargeTransactions)
|
||||
r.GET("/api/coin/trans/export", web.RechargeCoinTransExport)
|
||||
r.GET("/api/recharge/transactions/export", web.RechargeCoinTransExport)
|
||||
r.POST("/api/upload/image", web.UploadImage)
|
||||
r.POST("/api/feedback/add", web.FeedbackAdd)
|
||||
|
||||
// 播放页 BFF
|
||||
r.GET("/api/playlet/guess-like/list", web.GuessLikeList)
|
||||
r.GET("/api/comment/list", web.CommentList)
|
||||
r.POST("/api/comment/send", web.CommentSend)
|
||||
r.POST("/api/comment/like/set", web.CommentLikeSet)
|
||||
r.POST("/api/playlet/chapter/like/set", web.ChapterLikeSet)
|
||||
r.POST("/api/playlet/chapter/collect/set", web.ChapterCollectSet)
|
||||
r.POST("/api/playlet/chapter/watch/report", web.ChapterWatchReport)
|
||||
r.POST("/api/playlet/chapter/unlock", web.ChapterUnlock)
|
||||
r.POST("/api/playlet/like/set", web.PlayletLikeSet)
|
||||
r.POST("/api/playlet/collect/set", web.PlayletCollectSet)
|
||||
r.POST("/api/video/like/set", web.VideoLikeSet)
|
||||
r.POST("/api/video/collect/set", web.VideoCollectSet)
|
||||
r.GET("/api/web/search/suggest", web.SearchSuggest)
|
||||
|
||||
// 搜索引擎抓取、发现与站点所有权验证。
|
||||
r.GET("/robots.txt", web.RobotsTXT)
|
||||
r.GET("/llms.txt", web.LLMSTXT)
|
||||
if key := seoser.VerifyFromConfig().IndexNowKey; key != "" {
|
||||
r.GET("/"+key+".txt", web.SEOVerifyFile)
|
||||
}
|
||||
|
||||
r.NoRoute(web.NotFound)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
webtpl "videoweb/app/template"
|
||||
)
|
||||
|
||||
func mustHTMLTemplate(funcMap template.FuncMap) *template.Template {
|
||||
tmpl := template.New("").Funcs(funcMap)
|
||||
err := fs.WalkDir(webtpl.FS, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil || d.IsDir() {
|
||||
return err
|
||||
}
|
||||
if !strings.HasSuffix(strings.ToLower(d.Name()), ".html") {
|
||||
return nil
|
||||
}
|
||||
body, err := webtpl.FS.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tmpl.New(filepath.Base(path)).Parse(string(body))
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if tmpl.Lookup("index.html") == nil {
|
||||
panic("embedded html templates are empty")
|
||||
}
|
||||
return tmpl
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"videoweb/app/appg"
|
||||
commonhttp "videoweb/pub/common/http"
|
||||
"videoweb/pub/common/log"
|
||||
"videoweb/pub/common/m3u8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func registerM3U8Routes(r *gin.Engine) {
|
||||
r.GET("/h5/m3u8/*path", proxyM3U8)
|
||||
r.GET("/enkey", serveM3U8Key)
|
||||
r.GET("/newenkey", serveNewM3U8Key)
|
||||
}
|
||||
|
||||
func proxyM3U8(c *gin.Context) {
|
||||
rawPath := strings.TrimPrefix(c.Param("path"), "/")
|
||||
if rawPath == "" {
|
||||
c.Status(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if c.Request.URL.RawQuery != "" {
|
||||
rawPath += "?" + c.Request.URL.RawQuery
|
||||
}
|
||||
|
||||
serverAddr := strings.TrimRight(strings.TrimSpace(appg.Conf.ServerAddr), "/")
|
||||
if serverAddr == "" {
|
||||
log.Warn("proxyM3U8 empty serverAddr")
|
||||
c.Status(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
targetURL := serverAddr + "/h5/m3u8/" + rawPath
|
||||
|
||||
// 播放地址本身带签名 token;勿强制带登录 Authorization。
|
||||
body, status, err := fetchM3U8Upstream(c, targetURL, "")
|
||||
if err != nil {
|
||||
log.Warn("proxyM3U8 request failed", log.Any("target", targetURL), log.E(err))
|
||||
c.Status(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
if status != http.StatusOK {
|
||||
c.Status(status)
|
||||
return
|
||||
}
|
||||
if code, ok := jsonErrorCode(body); ok {
|
||||
log.Warn("proxyM3U8 upstream error",
|
||||
log.Any("target", targetURL),
|
||||
log.Any("code", code),
|
||||
log.Any("body", string(body)))
|
||||
c.Data(http.StatusBadGateway, "application/json; charset=utf-8", body)
|
||||
return
|
||||
}
|
||||
|
||||
contentType := detectMediaContentType(rawPath)
|
||||
if isM3U8Content(rawPath, body) {
|
||||
contentType = "application/vnd.apple.mpegurl"
|
||||
}
|
||||
|
||||
c.Data(http.StatusOK, contentType, body)
|
||||
}
|
||||
|
||||
func fetchM3U8Upstream(c *gin.Context, targetURL, auth string) ([]byte, int, error) {
|
||||
header := map[string]string{
|
||||
"Accept": "*/*",
|
||||
}
|
||||
if auth != "" {
|
||||
header["Authorization"] = auth
|
||||
}
|
||||
applyClientForwardHeaders(header, c)
|
||||
resp, err := commonhttp.GetLargeFile(targetURL, header)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return resp.Data, resp.StatusCode, nil
|
||||
}
|
||||
|
||||
func jsonErrorCode(body []byte) (int, bool) {
|
||||
if len(body) == 0 || body[0] != '{' {
|
||||
return 0, false
|
||||
}
|
||||
var payload struct {
|
||||
Code int `json:"code"`
|
||||
}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return 0, false
|
||||
}
|
||||
if payload.Code == 200 || payload.Code == 0 {
|
||||
return 0, false
|
||||
}
|
||||
return payload.Code, true
|
||||
}
|
||||
|
||||
func isM3U8Content(rawPath string, body []byte) bool {
|
||||
if strings.Contains(strings.Split(rawPath, "?")[0], ".m3u8") {
|
||||
return true
|
||||
}
|
||||
return len(body) > 0 && body[0] == '#'
|
||||
}
|
||||
|
||||
func detectMediaContentType(rawPath string) string {
|
||||
pathOnly := strings.Split(rawPath, "?")[0]
|
||||
switch {
|
||||
case strings.HasSuffix(pathOnly, ".m3u8"):
|
||||
return "application/vnd.apple.mpegurl"
|
||||
case strings.HasSuffix(pathOnly, ".ts"):
|
||||
return "video/mp2t"
|
||||
default:
|
||||
return "application/octet-stream"
|
||||
}
|
||||
}
|
||||
|
||||
func serveM3U8Key(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Cache-Control", "no-store")
|
||||
|
||||
if key, ok := fetchUpstreamEnkey(c, c.Request.URL.RawQuery); ok {
|
||||
c.Data(http.StatusOK, "application/octet-stream", key)
|
||||
return
|
||||
}
|
||||
|
||||
buffer, err := m3u8.Enkey(c.Request.Context())
|
||||
if err != nil || buffer == nil || buffer.Len() == 0 {
|
||||
log.Warn("serveM3U8Key local key unavailable", log.E(err))
|
||||
c.Status(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "application/octet-stream", buffer.Bytes())
|
||||
}
|
||||
|
||||
func serveNewM3U8Key(c *gin.Context) {
|
||||
c.Header("Access-Control-Allow-Origin", "*")
|
||||
c.Header("Cache-Control", "no-store")
|
||||
|
||||
key, ok := fetchUpstreamKey(c, "/newenkey", c.Request.URL.RawQuery)
|
||||
if !ok {
|
||||
c.Status(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
c.Data(http.StatusOK, "application/octet-stream", key)
|
||||
}
|
||||
|
||||
func fetchUpstreamEnkey(c *gin.Context, rawQuery string) ([]byte, bool) {
|
||||
return fetchUpstreamKey(c, "/enkey", rawQuery)
|
||||
}
|
||||
|
||||
func fetchUpstreamKey(c *gin.Context, keyPath, rawQuery string) ([]byte, bool) {
|
||||
serverAddr := strings.TrimRight(strings.TrimSpace(appg.Conf.ServerAddr), "/")
|
||||
if serverAddr == "" {
|
||||
return nil, false
|
||||
}
|
||||
// 上游对 /enkey、/newenkey 会 301 到带尾斜杠路径;GetLargeFile 不跟随跳转。
|
||||
if !strings.HasSuffix(keyPath, "/") {
|
||||
keyPath += "/"
|
||||
}
|
||||
targetURL := serverAddr + keyPath
|
||||
if rawQuery = strings.TrimSpace(rawQuery); rawQuery != "" {
|
||||
targetURL += "?" + rawQuery
|
||||
}
|
||||
header := map[string]string{
|
||||
"Accept": "*/*",
|
||||
}
|
||||
applyClientForwardHeaders(header, c)
|
||||
resp, err := commonhttp.GetLargeFile(targetURL, header)
|
||||
if err != nil {
|
||||
log.Warn("fetchUpstreamKey request failed", log.Any("target", targetURL), log.E(err))
|
||||
return nil, false
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK || len(resp.Data) == 0 || jsonErrorCodeBody(resp.Data) {
|
||||
log.Warn("fetchUpstreamKey invalid response",
|
||||
log.Any("target", targetURL),
|
||||
log.Any("status", resp.StatusCode),
|
||||
log.Any("len", len(resp.Data)))
|
||||
return nil, false
|
||||
}
|
||||
return resp.Data, true
|
||||
}
|
||||
|
||||
func jsonErrorCodeBody(body []byte) bool {
|
||||
_, ok := jsonErrorCode(body)
|
||||
return ok
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"videoweb/app/api/web"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// 其他项目(hgdjnet-server)写入 H5 目录的 sitemap 产物路径。
|
||||
var sitemapShardDirs = []string{
|
||||
"./template/pages/sitemaps",
|
||||
}
|
||||
|
||||
var sitemapIndexFiles = []string{
|
||||
"./template/pages/sitemaps/sitemap.xml",
|
||||
"./template/pages/sitemap.xml",
|
||||
}
|
||||
|
||||
// registerSitemapRoutes 只暴露静态 sitemap,不在本项目生成。
|
||||
func registerSitemapRoutes(r *gin.Engine) {
|
||||
r.GET("/sitemap.xml", serveSitemapIndex)
|
||||
r.GET("/sitemaps/:name", serveSitemapShard)
|
||||
}
|
||||
|
||||
func serveSitemapIndex(c *gin.Context) {
|
||||
path, ok := firstExistingFile(sitemapIndexFiles...)
|
||||
if !ok {
|
||||
web.NotFound(c)
|
||||
return
|
||||
}
|
||||
c.File(path)
|
||||
}
|
||||
|
||||
func serveSitemapShard(c *gin.Context) {
|
||||
name := c.Param("name")
|
||||
if !isValidSitemapShardName(name) {
|
||||
web.NotFound(c)
|
||||
return
|
||||
}
|
||||
var candidates []string
|
||||
for _, dir := range sitemapShardDirs {
|
||||
candidates = append(candidates, filepath.Join(dir, name))
|
||||
}
|
||||
path, ok := firstExistingFile(candidates...)
|
||||
if !ok {
|
||||
web.NotFound(c)
|
||||
return
|
||||
}
|
||||
c.File(path)
|
||||
}
|
||||
|
||||
func firstExistingFile(paths ...string) (string, bool) {
|
||||
for _, path := range paths {
|
||||
info, err := os.Stat(path)
|
||||
if err == nil && !info.IsDir() {
|
||||
return path, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// isValidSitemapShardName 校验分片文件名,防止路径遍历。
|
||||
func isValidSitemapShardName(name string) bool {
|
||||
if !strings.HasPrefix(name, "sitemap-") || !strings.HasSuffix(name, ".xml") {
|
||||
return false
|
||||
}
|
||||
base := strings.TrimSuffix(name, ".xml")
|
||||
if len(base) <= len("sitemap-") {
|
||||
return false
|
||||
}
|
||||
for _, ch := range base[len("sitemap-"):] {
|
||||
if !((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '-') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user