2019年11月

GoLang类型转换


string到int

int,err:=strconv.Atoi(string)

string到int64

int64, err := strconv.ParseInt(string, 10, 64)

int到string

string:=strconv.Itoa(int)

int64到string

string:=strconv.FormatInt(int64,10)

string到float32/float64

float32, err = ParseFloat(string, 32)
float64,err = ParseFloat(string,64)

int64转int

int:=int(int64)

int转int64

int64:=int64(int)

js扁平化json数据转树形结构


//扁平化json数据转树形结构
function treeData(list, id, pid, children) {
    var clone = JSON.parse(JSON.stringify(list));
    return clone.filter(function (father) {
        var childlist = clone.filter(function (child) {
            return father[id] == child[pid];
        });
        if (childlist.length > 0) {
            father[children] = childlist;
        }
        return father[pid] == 0;
    });
}

var dataa=[{id:1,parentId:0,name:"测试1"},{id:2,parentId:1,name:"测试2"}]

$(function(){
    var t = treeData(dataa,"id","parentId","children");
    console.log(t)
})

PS:错误的JSON

//错误1
[{id:1,name:"测试1"}]

//错误2
[{name:"测试1",parentId:0}]

Golang使用使用Nsq发布消息和订阅消息


生产者

package main
 
import (
    "github.com/nsqio/go-nsq"
    "fmt"
)
 
var (
    //nsqd的地址,使用了tcp监听的端口
    tcpNsqdAddrr = "10.10.6.147:4150"
)
 
func main() {
    //初始化配置
    config := nsq.NewConfig()
    for i := 0; i < 100; i++ {
        //创建100个生产者
        tPro, err := nsq.NewProducer(tcpNsqdAddrr, config)
        if err != nil {
            fmt.Println(err)
        }
        //主题
        topic := "Insert"
        //主题内容
        tCommand := "new data!"
        //发布消息
        err = tPro.Publish(topic, []byte(tCommand))
        if err != nil {
            fmt.Println(err)
        }
    }
 
}

消费者

package main
 
import (
    "github.com/nsqio/go-nsq"
    "fmt"
    "sync"
    "time"
)
 
var (
    //nsqd的地址,使用了tcp监听的端口
    tcpNsqdAddrr = "10.10.6.147:4150"
)
 
//声明一个结构体,实现HandleMessage接口方法(根据文档的要求)
type NsqHandler struct {
    //消息数
    msqCount int64
    //标识ID
    nsqHandlerID string
}
 
//实现HandleMessage方法
//message是接收到的消息
func (s *NsqHandler) HandleMessage(message *nsq.Message) error {
    //没收到一条消息+1
    s.msqCount++
    //打印输出信息和ID
    fmt.Println(s.msqCount,s.nsqHandlerID)
    //打印消息的一些基本信息
    fmt.Printf("msg.Timestamp=%v, msg.nsqaddress=%s,msg.body=%s \n", time.Unix(0  , message.Timestamp).Format("2006-01-02 03:04:05") , message.NSQDAddress, string(message.Body))
    return nil
}
 
func main() {
 
    //初始化配置
    config := nsq.NewConfig()
    //创造消费者,参数一时订阅的主题,参数二是使用的通道
    com, err := nsq.NewConsumer("Insert", "channel1", config)
    if err != nil {
        fmt.Println(err)
    }
    //添加处理回调
    com.AddHandler(&NsqHandler{nsqHandlerID:"One"})
    //连接对应的nsqd
    err = com.ConnectToNSQD(tcpNsqdAddrr)
    if err != nil {
        fmt.Println(err)
    }
 
    //只是为了不结束此进程,这里没有意义
    var wg  = &sync.WaitGroup{}
    wg.Add(1)
    wg.Wait()
    
    /*
    result:
    
    msg.Timestamp=2018-11-02 04:37:18, msg.nsqaddress=10.10.6.147:4150,msg.body=new data! 
    98 One
    msg.Timestamp=2018-11-02 04:37:18, msg.nsqaddress=10.10.6.147:4150,msg.body=new data! 
    99 One
    msg.Timestamp=2018-11-02 04:37:18, msg.nsqaddress=10.10.6.147:4150,msg.body=new data! 
    100 One
    msg.Timestamp=2018-11-02 04:37:18, msg.nsqaddress=10.10.6.147:4150,msg.body=new data!
    
    */
    
}

BeeGo过滤器做用户权限控制


package routers

import (
    "项目/controllers"
    "项目/models"

    "github.com/astaxie/beego"
    "github.com/astaxie/beego/context"
)

func init() {
    var FilterUser = func(ctx *context.Context) {
        u, _ := ctx.Input.Session("user").(models.LpUser)
        if u.Id == 0 {
            ctx.Redirect(302, "/login")
        }
    }
        beego.InsertFilter("/user/*", beego.BeforeRouter, FilterUser)
}

golang在数字、大写字母、小写字母范围内生成num位的随机字符串


package utils

import "math/rand"
import "time"
import "strconv"
import "strings"

func RandomString(length int) string {
    // 48 ~ 57 数字
    // 65 ~ 90 A ~ Z
    // 97 ~ 122 a ~ z
    // 一共62个字符,在0~61进行随机,小于10时,在数字范围随机,
    // 小于36在大写范围内随机,其他在小写范围随机
    rand.Seed(time.Now().UnixNano())
    result := make([]string, 0, length)
    for i := 0; i < length; i++ {
        t := rand.Intn(62)
        if t < 10 {
            result = append(result, strconv.Itoa(rand.Intn(10)))
        } else if t < 36 {
            result = append(result, string(rand.Intn(26)+65))
        } else {
            result = append(result, string(rand.Intn(26)+97))
        }
    }
    return strings.Join(result, "")
}

js 时间段(年-月 - 年-月)获取所有(年-月)


//输入:2019-01 - 2019-03
//输出:["2019-01","2019-02","2019-03"]

function utils_LayuiTimeslot_To_StrArray(Timeslot){
    var resultArray = []
    var arrstr = Timeslot.split(" - ")

    var ksYear  = arrstr[0].trim().substring(0,4)
    var ksMonth = arrstr[0].trim().substring(5,7)

    var jsYear  = arrstr[1].trim().substring(0,4)
    var jsMonth = arrstr[1].trim().substring(5,7)
    
    var tYear = parseInt(ksYear) 
    
    for (var i = 0; i<= jsYear - ksYear; i++) {
        var eMonth = 12
        var sMonth = 1

        if(ksYear == jsYear){
            eMonth = jsMonth
            sMonth = ksMonth
        }else if(i == jsYear - ksYear){ // 最后一次循环
            eMonth = jsMonth
        }else if(i == 0){ // 第一次循环
            sMonth = ksMonth
        } 
        
        for (var m= sMonth; m <= eMonth ; m ++) {
            var mm = m.toString();
            if(mm.length == 1){
                mm = "0" + m.toString();
            }
            resultArray.push(tYear + "-" + mm)
        }

        tYear = tYear + 1
        
    }
    return resultArray
}