// 对外服务 package main import ( "crypto/tls" _ "embed" "encoding/json" "fmt" "log" "net/http" "github.com/wailsapp/wails/v2/pkg/runtime" ) const ( LISTEN_ADDR = ":8080" ) type ( SpiderConfigItem struct { Key string `json:"key"` Css string `json:"css"` } ) var ( //go:embed cert.pem certBytes []byte //go:embed key.pem keyBytes []byte ) func runHttpServe() { // 设置HTTP服务器 mux := http.NewServeMux() // 解析证书 cert, err := tls.X509KeyPair(certBytes, keyBytes) if err != nil { log.Println(err.Error()) return } // 创建一个TLS配置 tlsConfig := &tls.Config{ // 可以在这里添加其他TLS配置 Certificates: []tls.Certificate{cert}, ServerName: "localhost", InsecureSkipVerify: true, } server := &http.Server{ Addr: LISTEN_ADDR, Handler: mux, TLSConfig: tlsConfig, } //这里注册HTTP服务 mux.HandleFunc("/save", SaveSpiderConfig) mux.HandleFunc("/load", LoadSpiderConfig) // log.Println("Starting HTTPS server on ", LISTEN_ADDR) err = server.ListenAndServeTLS("", "") if err != nil { log.Println("Failed to start server: ", err.Error()) return } } // LoadCurrentSpiderConfig,json处理 func SaveSpiderConfig(w http.ResponseWriter, r *http.Request) { log.Println("保存设置") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application/json") var req = new(SpiderConfigItem) err := json.NewDecoder(r.Body).Decode(req) if err != nil { log.Println("序列化失败") http.Error(w, err.Error(), http.StatusBadRequest) return } log.Println("CSS", req.Key, req.Css) //TODO 业务操作 switch req.Key { case "listItemCss": currentSpiderConfig.ListItemCss = req.Css case "listLinkCss": currentSpiderConfig.ListLinkCss = req.Css case "listPublishTimeCss": currentSpiderConfig.ListPubtimeCss = req.Css case "listNextPageCss": currentSpiderConfig.ListNextPageCss = req.Css case "titleCss": currentSpiderConfig.TitleCss = req.Css case "publishUnitCss": currentSpiderConfig.PublishUnitCss = req.Css case "publishTimeCss": currentSpiderConfig.PublishTimeCss = req.Css case "contentCss": currentSpiderConfig.ContentCss = req.Css case "attachCss": currentSpiderConfig.AttachCss = req.Css } fmt.Fprint(w, "{'code':200}") db.SaveOrUpdate(currentSpiderConfig) //TODO 通知开发工具端,CSS选择器有变动 runtime.EventsEmit(app.ctx, "spiderConfigChange", currentSpiderConfig) } // LoadCurrentSpiderConfig,加载,返回当前配置项 func LoadSpiderConfig(w http.ResponseWriter, r *http.Request) { log.Println("加载当前配置项") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Content-Type", "application/json") err := json.NewEncoder(w).Encode(currentSpiderConfig) if err != nil { log.Println("反向序列化失败") http.Error(w, err.Error(), http.StatusBadRequest) return } }