This commit is contained in:
xing 2022-07-07 16:52:18 +08:00
parent 18eb1cb6ed
commit 6d76a35005
2 changed files with 33 additions and 39 deletions

33
dist/static.go vendored
View File

@ -1,33 +0,0 @@
package dist
import (
"embed"
"errors"
"io/fs"
"path/filepath"
"strings"
)
type Dist struct {
embed.FS
}
//go:embed css js favicon.ico index.html
var Static embed.FS
func (r Dist) Open(name string) (fs.File, error) {
if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
return nil, errors.New("http: invalid character in file path")
}
fullName := strings.TrimLeft(name, "/")
prifix := strings.Split(fullName, ".")
l := len(prifix)
p := prifix[l-1]
if p == "js" || p == "css" {
fullName = p + "/" + fullName
} else if p == "map" {
fullName = "js/" + fullName
}
file, err := r.FS.Open(fullName)
return file, err
}

39
main.go
View File

@ -1,14 +1,17 @@
package main
import (
"embed"
"errors"
"github.com/PuerkitoBio/goquery"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github/fthvgb1/newsfetch/dist"
"io/fs"
"io/ioutil"
"log"
"net/http"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
@ -59,6 +62,32 @@ type message struct {
Data interface{}
}
type dist struct {
embed.FS
path string
}
//go:embed dist/*
var st embed.FS
func (r dist) Open(name string) (fs.File, error) {
if filepath.Separator != '/' && strings.ContainsRune(name, filepath.Separator) {
return nil, errors.New("http: invalid character in file path")
}
fullName := strings.TrimLeft(name, "/")
prifix := strings.Split(fullName, ".")
l := len(prifix)
p := prifix[l-1]
if p == "js" || p == "css" {
fullName = p + "/" + fullName
} else if p == "map" {
fullName = "js/" + fullName
}
fullName = r.path + "/" + fullName
file, err := r.FS.Open(fullName)
return file, err
}
func setMap[T mapT](obj *mapXS[T], key string, v T) {
obj.Lock()
(*obj.mapX)[key] = v
@ -267,14 +296,12 @@ func (f *fetchHandler) cronFetch(conn string, c chan int) {
func main() {
h := newFetchHandler("https://www.baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&rsv_dl=ns_pc&word=")
router := gin.Default()
static := dist.Dist{
FS: dist.Static,
static := dist{
FS: st,
path: "dist",
}
//router.Static("/css", "./dist/css")
//router.Static("/js", "./dist/js")
router.StaticFS("/js", http.FS(static))
router.StaticFS("/css", http.FS(static))
//router.StaticFile("/favicon.ico", "dist/favicon.ico")
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true