变量替换代码片段

前端之家收集整理的这篇文章主要介绍了变量替换代码片段前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

代码片段分享


package main

import (
	"bufio"
	"bytes"
	"io/IoUtil"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
)

func main() {
	M := ReadStaticAndVariable("staticTovariable")
	if len(os.Args) != 2 {
		println("args error.")
		return
	}
	list,err := GetConfigFiles(os.Args[1])
	if err != nil {
		println(err.Error())
		return
	}
	StaticToVariable(list,M)
}

func GetConfigFiles(path string) ([]string,error) {
	if !strings.HasSuffix(path,"/") {
		path = path + "/"
	}
	var list []string
	files,err := IoUtil.ReadDir(path)
	if err != nil {
		return list,err
	}
	for _,v := range files {
		if v.IsDir() {
			continue
		}
		list = append(list,path+v.Name())
	}
	return list,nil
}

func ReadStaticAndVariable(path string) map[string]string {
	File,err := os.Open(path)
	if err != nil {
		return nil
	}
	defer File.Close()
	buf := bufio.NewReader(File)
	M := make(map[string]string)
	for {
		line,_,err := buf.ReadLine()
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			return nil
		}
		list := bytes.Split(line,[]byte("="))
		if len(list) != 2 {
			continue
		}
		k := bytes.TrimSpace(list[0])
		v := bytes.TrimSpace(list[1])
		M[string(k)] = string(v)
	}
	return M
}

//设置并发处理的个数.
const number int = 5

func StaticToVariable(pathList []string,M map[string]string) {
	c := make(chan int,number)
	for _,name := range pathList {
		c <- 1
		go staticToVariable(c,name,M)
	}
	for {
		if len(c) != 0 {
			time.Sleep(1e9)
			continue
		}
		break
	}
}

func staticToVariable(c chan int,path string,M map[string]string) {
	defer func(c chan int) {
		<-c
	}(c)
	path = filepath.ToSlash(path)
	File,err := os.Open(path)
	if err != nil {
		return
	}
	tmpName := filepath.Dir(path) + "/." + filepath.Base(path)
	tmp,err := os.OpenFile(tmpName,os.O_RDWR|os.O_CREATE|os.O_TRUNC,0644)
	if err != nil {
		File.Close()
		return
	}
	buf := getBuf()
	defer putBuf(buf)
	for {
		n,err := File.Read(buf)
		if err != nil {
			if err.Error() == "EOF" {
				break
			}
			File.Close()
			return
		}
		for k,v := range M {
			buf = bytes.Replace(buf[:n],[]byte(k),[]byte(v),-1)
		}
		tmp.Write(bytes.TrimSpace(buf))
		tmp.Sync()
	}
	File.Close()
	tmp.Close()
	os.Remove(path)
	os.Rename(tmpName,path)
	return
}

var BufPool *sync.Pool = new(sync.Pool)

func getBuf() []byte {
	b := BufPool.Get()
	if b != nil {
		return b.([]byte)
	}
	return make([]byte,512)
}

func putBuf(buf []byte) {
	BufPool.Put(buf)
}

func checkIsBinary(path string) bool {
	File,err := os.Open(path)
	if err != nil {
		return true
	}
	buf := make([]byte,1024)
	n,err := File.Read(buf)
	if err != nil {
		return true
	}
	if bytes.Contains(buf[:n],[]byte{0x0}) {
		return true
	}
	return false
}
原文链接:https://www.f2er.com/go/189968.html

猜你在找的Go相关文章