golang日志中心取日志代码分享

fyxichen · · 1881 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

package main

import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)

var tempDir string = "tmp"

const zone int64 = +8

func init() {
	os.MkdirAll(tempDir, 0644)
}

const bodyType = "application/x-www-form-urlencoded"

func main() {
	go Server()
	var x job = job{Id: "cp_19216823", Name: []string{`game/logs/log`,
		`gate/logs/log`, `game-fight`, `mail/logs/log`, `room-manage/logs/log`, `/oem8.log`},
		Path: `C:\test\server`, Tag: "getfile"}
	b, _ := json.Marshal(x)
	buf := bytes.NewReader(b)
	resp, err := http.Post("http://172.18.0.12:1789/", bodyType, buf)
	if err != nil {
		fmt.Println(err)
	}
	resp.Body.Close()
}

type job struct {
	Id   string   `json:id`
	Name []string `json:name`
	Path string   `json:path`
	Tag  string   `json:"tag,omitempty"`
	temp string   `json:tempfile`
}

func (self *job) Init() {
	self.Path = filepath.ToSlash(self.Path)
	if !filepath.HasPrefix(self.Path, "/") {
		self.Path = self.Path + "/"
	}
	self.temp = tempDir + "/" + self.Id + "/"
	os.MkdirAll(self.temp, 0644)
}

func (self *job) Copy() []string {
	self.Init()
	var list []string
	for _, v := range self.Name {
		v = filepath.ToSlash(v)
		var path, dst string
		if filepath.IsAbs(v) {
			list := strings.Split(v, "/")
			if len(list) <= 1 {
				continue
			}
			dst = self.temp + strings.Join(list[1:], "/")
			err := CopyFile(v, dst)
			if err != nil {
				list = append(list, v)
			}
			continue
		}
		path = self.Path + v
		basedir := filepath.ToSlash(filepath.Dir(v))
		if basedir != filepath.Base(v) {
			os.MkdirAll(self.temp+basedir, 0644)
		}
		dst = self.temp + v
		err := CopyFile(path, dst)
		if err != nil {
			list = append(list, v)
			continue
		}
	}
	return list
}

func (self *job) ListFile() map[string][]string {
	self.Init()
	var m map[string][]string = make(map[string][]string)
	for _, v := range self.Name {
		var list []string
		v = filepath.ToSlash(v)
		if filepath.IsAbs(v) {
			_, err := os.Stat(v)
			if err != nil {
				continue
			}
			m[v] = append(list, v)
			continue
		}
		path := self.Path + v
		info, err := os.Stat(path)
		if err != nil {
			continue
		}
		if !info.IsDir() {
			list = append(list, path)
			m[path] = list
			continue
		}
		l, err := ioutil.ReadDir(path)
		if err != nil {
			continue
		}
		for _, name := range l {
			list = append(list, name.Name())
		}
		m[path] = list
	}
	return m
}

func (self *job) Run() {
	switch self.Tag {
	case "getfile":
		self.Copy()
		err := Zip(tempDir+"/"+self.Id, tempDir+"/"+self.Id+".zip")
		if err != nil {
			fmt.Println(err)
		}
		os.RemoveAll(tempDir + "/" + self.Id)
	case "listfile":
		self.ListFile()
	}
}

func CopyFile(src, dst string) error {
	sFile, err := os.Open(src)
	if err != nil {
		return err
	}
	defer sFile.Close()
	dFile, err := os.Create(dst)
	if err != nil {
		return err
	}
	defer dFile.Close()
	io.Copy(dFile, sFile)
	return nil
}

func Zip(source, target string) error {
	zipfile, err := os.Create(target)
	if err != nil {
		return err
	}
	defer zipfile.Close()
	archive := zip.NewWriter(zipfile)
	defer archive.Close()

	return filepath.Walk(source, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		header, err := zip.FileInfoHeader(info)
		if err != nil {
			return err
		}
		if !info.IsDir() {
			header.Method = zip.Deflate
		}
		header.SetModTime(time.Unix(info.ModTime().Unix()+(zone*60*60), 0))
		header.Name = path
		writer, err := archive.CreateHeader(header)
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}
		file, err := os.Open(path)
		if err != nil {
			return err
		}
		defer file.Close()
		_, err = io.Copy(writer, file)
		return err
	})
}

func route(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	ip, _, err := net.SplitHostPort(r.RemoteAddr)
	if err != nil {
		return
	}
	if !ipIsLanIP(ip) {
		return
	}
	buf, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return
	}
	Job := new(job)
	err = json.Unmarshal(buf, Job)
	if err != nil {
		return
	}
	Job.Run()
}

func Server() {
	http.HandleFunc("/", route)
	http.ListenAndServe(":1789", nil)
}

var (
	mask  net.IPMask = net.CIDRMask(16, 32)
	IP192 net.IPNet  = net.IPNet{net.ParseIP("192.168.0.0"), mask}
	IP172 net.IPNet  = net.IPNet{net.ParseIP("172.18.0.0"), mask}
	IP10  net.IPNet  = net.IPNet{net.ParseIP("10.0.0.0"), mask}
)

func ipIsLanIP(str string) bool {
	ip := net.ParseIP(str)
	return IP192.Contains(ip) || IP172.Contains(ip) || IP10.Contains(ip)
}


有疑问加站长微信联系(非本文作者)

本文来自:CSDN博客

感谢作者:fyxichen

查看原文:golang日志中心取日志代码分享

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1881 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传