package util import ( "context" "encoding/binary" "math/rand" "net" "strconv" "strings" "time" ) // GenerateSpanID define func of generate spanID func GenerateSpanID(addr string) string { strAddr := strings.Split(addr, ":") ip := strAddr[0] ipLong, _ := IP2Long(ip) times := uint64(time.Now().UnixNano()) rand.NewSource(time.Now().UnixNano()) spanID := ((times ^ uint64(ipLong)) << 32) | uint64(rand.Int31()) return strconv.FormatUint(spanID, 16) } // IP2Long define func of convert ip to unit32 type func IP2Long(ip string) (uint32, error) { ipAddr, err := net.ResolveIPAddr("ip", ip) if err != nil { return 0, err } return binary.BigEndian.Uint32(ipAddr.IP.To4()), nil } // GetTraceInfoFromCtx define func of get trace info from context func GetTraceInfoFromCtx(ctx context.Context) (traceID, spanID, pSpanID string) { if ctx.Value("traceid") != nil { traceID = ctx.Value("traceid").(string) } if ctx.Value("spanid") != nil { spanID = ctx.Value("spanid").(string) } if ctx.Value("pspanid") != nil { pSpanID = ctx.Value("pspanid").(string) } return }