Commit 6684831a by lichenggang

移动文件

parent a593cfb9
package code
import (
"log"
"os"
"time"
)
// 监控日志文件
func monitor(filePath string, filename string) {
defer func() {
if err := recover(); err != nil {
log.Printf("[seelog] error:%+v", err)
}
}()
var fileInfo os.FileInfo
var err error
for i := 1; i <= 10; i++ {
fileInfo, err = os.Stat(filePath)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
continue
}
break
}
offset := fileInfo.Size()
for {
fileInfo, err = os.Stat(filePath)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
continue
}
newOffset := fileInfo.Size()
if offset < newOffset {
msg := make([]byte, newOffset-offset)
file, err := os.Open(filePath)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
continue
}
_, err = file.Seek(offset, 0)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
}
_, err = file.Read(msg)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
}
str_msg := string(msg)
s := filename + "$$" + str_msg
manager.broadcast <- []byte(s)
offset = newOffset
file.Close()
}
offset = newOffset
time.Sleep(200 * time.Millisecond)
}
}
package code
import (
"log"
"sync"
)
// 启动seelog
func See(filePath string, port int) {
// 检查参数
if !checkParam(filePath, port) {
return
}
var wg sync.WaitGroup
wg.Add(1)
go server(port, filePath)
wg.Wait()
}
// 参数验证
func checkParam(filePath string, port int) bool {
if filePath == "" {
log.Println("filePath 不可为空")
return false
}
if port == 0 {
log.Println("port 不可为空")
return false
}
return true
}
package code
import (
"bytes"
"fmt"
"golang.org/x/net/websocket"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
func get_files(direct_path string) []string {
var li_file []string
files, _ := ioutil.ReadDir(direct_path)
for _, f := range files {
li_file = append(li_file, f.Name())
}
return li_file
}
func return_res(w http.ResponseWriter, template_path string, data interface{}) {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(200)
tmpl, err := template.ParseFiles(template_path)
if err != nil {
log.Println("err:", err)
return
}
tmpl.Execute(w, data)
}
func return_error_res(w http.ResponseWriter, str_file string) {
var ct bytes.Buffer
ct.WriteString("<script>alert(\"File not exist: ")
ct.WriteString(str_file)
ct.WriteString("\")</script>")
w.Write([]byte(ct.String()))
return
}
// 开启 httpServer
func server(port int, directory string) {
defer func() {
if err := recover(); err != nil {
log.Printf("[seelog] error:%+v", err)
}
}()
// 返回页面
//http.HandleFunc("/log",page)
http.HandleFunc("/log", func(w http.ResponseWriter, r *http.Request) {
queryform, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
log.Fatal(err)
}
if li_innerip, ok := queryform["innerip"]; ok {
innerip := li_innerip[0]
ip_files := get_files(directory + "/" + innerip)
if li_server_direc, ok := queryform["server_direc"]; ok {
server_direc := li_server_direc[0]
ip_server_files := get_files(directory + "/" + innerip + "/" + server_direc)
if li_filename, ok := queryform["filename"]; ok {
file := li_filename[0]
str_filepath := innerip + "~~" + server_direc + "~~" + file
filename := innerip + "/" + server_direc + "/" + file
_, err := os.Stat(directory + "/" + filename)
if err != nil {
return_error_res(w, filename)
}
fmt.Printf("view log [%s]\n", file)
return_res(w, "templates/page.html", str_filepath)
} else {
return_res(w, "templates/server_direc.html", strings.Join(ip_server_files, "~~"))
}
} else {
return_res(w, "templates/innnerip.html", strings.Join(ip_files, "~~"))
}
} else {
ips := get_files(directory)
return_res(w, "templates/index.html", strings.Join(ips, "~~"))
}
})
// socket链接
http.Handle("/ws", websocket.Handler(gen(directory, manager.filemap)))
go manager.start()
var bt bytes.Buffer
bt.WriteString("127.0.0.1:")
bt.WriteString(strconv.Itoa(port))
http.ListenAndServe(bt.String(), nil)
//log.Fatal()
}
// 创建client对象
func gen(directory string, file_map map[string]map[client]bool) func(ws *websocket.Conn) {
f := func(ws *websocket.Conn) {
cli := &client{time.Now().String(), ws, make(chan []byte, 1024)}
queryform, err := url.ParseQuery(ws.Request().URL.RawQuery)
if err != nil {
log.Fatal(err)
}
filename := queryform["file"][0]
//初始监听时加载全部内容
file_path := directory
for _, s := range strings.Split(filename, "~~") {
file_path += "/" + s
}
fileInfo, err := os.Stat(file_path)
if err != nil {
return
}
allcontent_file, err := os.Open(file_path)
offset := fileInfo.Size()
allcontent_msg := make([]byte, offset)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
}
_, err = allcontent_file.Read(allcontent_msg)
if err != nil {
log.Printf("[seelog] error:%v", err.Error())
}
all_content := filename + "$$" + string(allcontent_msg)
manager.broadcast <- []byte(all_content)
allcontent_file.Close()
// 监控文件
if _, ok := file_map[filename]; ok {
file_map[filename][*cli] = true
fmt.Printf("%s has been monitored\n", filename)
} else {
go monitor(file_path, filename)
l := make(map[client]bool)
l[*cli] = true
file_map[filename] = l
fmt.Printf("Add a new monitored file [%s]\n", filename)
}
//注册client并开始传输信息
manager.register <- cli
go cli.read()
cli.write()
}
return f
}
package code
import (
"fmt"
"golang.org/x/net/websocket"
"log"
"strings"
)
// websocket客户端
type client struct {
id string
socket *websocket.Conn
send chan []byte
}
// 客户端管理
type clientManager struct {
clients map[*client]bool
broadcast chan []byte
register chan *client
unregister chan *client
filemap map[string]map[client]bool
}
var manager = clientManager{
broadcast: make(chan []byte),
register: make(chan *client),
unregister: make(chan *client),
clients: make(map[*client]bool),
filemap: getfilemap(),
}
func getfilemap() map[string]map[client]bool {
file_map := make(map[string]map[client]bool)
return file_map
}
func (manager *clientManager) start() {
defer func() {
if err := recover(); err != nil {
log.Printf("[seelog] error:%+v", err)
}
}()
for {
select {
case conn := <-manager.register:
manager.clients[conn] = true
fmt.Printf("A client connect, current clients count is %d \n", len(manager.clients))
case conn := <-manager.unregister:
if _, ok := manager.clients[conn]; ok {
close(conn.send)
delete(manager.clients, conn)
for _, map_tmp := range manager.filemap {
delete(map_tmp, *conn)
}
fmt.Printf("A client disconnect, current clients count is %d \n", len(manager.clients))
}
case message := <-manager.broadcast:
str_msg := string(message)
tmp := strings.Split(str_msg, "$$")
filename := tmp[0]
msg := tmp[1]
map_tmp := manager.filemap[filename]
for conn, _ := range map_tmp {
select {
case conn.send <- []byte(msg):
default:
close(conn.send)
delete(manager.clients, &conn)
}
}
//for conn := range manager.clients {
// select {
// case conn.send <- message:
// default:
// close(conn.send)
// delete(manager.clients, conn)
// }
//}
}
}
}
func (c *client) write() {
//defer func() {
// manager.unregister <- c
// c.socket.Close()
//}()
for {
select {
case message, ok := <-c.send:
if !ok {
c.socket.WriteClose(1)
return
}
c.socket.Write(message)
}
}
}
func (c *client) read() {
defer func() {
manager.unregister <- c
}()
//
for {
var reply string
if err := websocket.Message.Receive(c.socket, &reply); err != nil {
fmt.Println("Error! Can't receive message...")
break
}
if reply != "heart" {
manager.unregister <- c
c.socket.Close()
} else {
fmt.Println("heart package...")
}
reply = ""
//time.Sleep(2000 * time.Millisecond)
//jsonMessage, _ := json.Marshal(&Message{Sender: c.id, Content: string(message)})
//manager.broadcast <- jsonMessage
}
}
//func (c *client) monitor(filePath string, filename string) {
// defer func() {
// if err := recover(); err != nil {
// log.Printf("[seelog] error:%+v", err)
// }
// }()
// var fileInfo os.FileInfo
// var err error
// for i := 1; i <= 10; i++ {
// fileInfo, err = os.Stat(filePath)
// if err != nil {
// log.Printf("[seelog] error:%v", err.Error())
// continue
// }
// break
// }
//
// offset := fileInfo.Size()
// for {
// fileInfo, err = os.Stat(filePath)
// if err != nil {
// log.Printf("[seelog] error:%v", err.Error())
// continue
// }
// newOffset := fileInfo.Size()
// if offset < newOffset {
// msg := make([]byte, newOffset-offset)
// file, err := os.Open(filePath)
// if err != nil {
// log.Printf("[seelog] error:%v", err.Error())
// continue
// }
// _, err = file.Seek(offset, 0)
// if err != nil {
// log.Printf("[seelog] error:%v", err.Error())
// }
//
// _, err = file.Read(msg)
// if err != nil {
// log.Printf("[seelog] error:%v", err.Error())
// }
// str_msg := string(msg)
// s := filename + "$$" + str_msg
//
// manager.broadcast <- []byte(s)
// offset = newOffset
// file.Close()
// }
// offset = newOffset
// time.Sleep(200 * time.Millisecond)
// }
//
//}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment