当前位置: 首页>>代码示例>>Golang>>正文


Golang bencode-go.Marshal函数代码示例

本文整理汇总了Golang中code/google/com/p/bencode-go.Marshal函数的典型用法代码示例。如果您正苦于以下问题:Golang Marshal函数的具体用法?Golang Marshal怎么用?Golang Marshal使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Marshal函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Scrape

// Scrape reports scrape for one or more files, using HTTP format
func (h HTTPTracker) Scrape(files []data.FileRecord) []byte {
	// Response struct
	scrape := scrapeResponse{
		Files: make(map[string]scrapeFile),
	}

	// WaitGroup to wait for all scrape file entries to be generated
	var wg sync.WaitGroup
	wg.Add(len(files))

	// Mutex for safe locking on map writes
	var mutex sync.RWMutex

	// Iterate all files in parallel
	for _, f := range files {
		go func(f data.FileRecord, scrape *scrapeResponse, mutex *sync.RWMutex, wg *sync.WaitGroup) {
			// Generate scrapeFile struct
			fileInfo := scrapeFile{}
			var err error

			// Seeders count
			fileInfo.Complete, err = f.Seeders()
			if err != nil {
				log.Println(err.Error())
			}

			// Completion count
			fileInfo.Downloaded, err = f.Completed()
			if err != nil {
				log.Println(err.Error())
			}

			// Leechers count
			fileInfo.Incomplete, err = f.Leechers()
			if err != nil {
				log.Println(err.Error())
			}

			// Add hash and file info to map
			mutex.Lock()
			scrape.Files[f.InfoHash] = fileInfo
			mutex.Unlock()

			// Inform waitgroup that this file is ready
			wg.Done()
		}(f, &scrape, &mutex, &wg)
	}

	// Wait for all information to be generated
	wg.Wait()

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, scrape); err != nil {
		log.Println(err.Error())
		return h.Error(ErrScrapeFailure.Error())
	}

	return buf.Bytes()
}
开发者ID:gernest,项目名称:goat,代码行数:61,代码来源:httpTracker.go

示例2: processRequest

func (s *share) processRequest(msg []byte) ([]byte, error) {
	fmt.Println("process request")
	var r Request
	err := bencode.Unmarshal(bytes.NewBuffer(msg), &r)
	if err != nil {
		return []byte{}, err
	}

	mdata, err := s.getFileMeta(r.File)
	check(err)

	if r.Index == -1 && r.Begin == -1 && r.Length == -1 {
		fmt.Println("want some meta")
		var data bytes.Buffer
		err = bencode.Marshal(&data, *mdata)
		fmt.Println(mdata)
		check(err)
		return s.createPiece(r.File, -1, -1, data.Bytes()), nil
	}

	buf := make([]byte, r.Length)
	f, err := os.Open(s.Path + "/" + r.File)
	check(err)
	_, err = f.ReadAt(buf, int64(r.Index*mdata.Piece_length+r.Begin))
	f.Close()
	check(err)

	fmt.Println("sending piece for", r.File, r.Index, r.Begin)

	return s.createPiece(r.File, r.Index, r.Begin, buf), nil
}
开发者ID:rdallman,项目名称:dropbit,代码行数:31,代码来源:share.go

示例3: Scrape

// Scrape reports scrape for one or more files, using HTTP format
func (h HTTPTracker) Scrape(files []data.FileRecord) []byte {
	// Response struct
	scrape := scrapeResponse{
		Files: make(map[string]scrapeFile),
	}

	// Iterate all files
	for _, file := range files {
		// Generate scrapeFile struct
		fileInfo := scrapeFile{
			Complete:   file.Seeders(),
			Downloaded: file.Completed(),
			Incomplete: file.Leechers(),
		}

		// Add hash and file info to map
		scrape.Files[file.InfoHash] = fileInfo
	}

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, scrape); err != nil {
		log.Println(err.Error())
		return h.Error("Tracker error: failed to create scrape response")
	}

	return buf.Bytes()
}
开发者ID:sdgoij,项目名称:goat,代码行数:29,代码来源:httpTracker.go

示例4: Bencode

// Encode to Bencode, but only encode non-default values.
func (m *MetaInfo) Bencode(w io.Writer) (err error) {
	var mi map[string]interface{} = map[string]interface{}{}
	id := m.Info.toMap()
	if len(id) > 0 {
		mi["info"] = id
	}
	// Do not encode InfoHash. Clients are supposed to calculate it themselves.
	if m.Announce != "" {
		mi["announce"] = m.Announce
	}
	if len(m.AnnounceList) > 0 {
		mi["announce-list"] = m.AnnounceList
	}
	if m.CreationDate != "" {
		mi["creation date"] = m.CreationDate
	}
	if m.Comment != "" {
		mi["comment"] = m.Comment
	}
	if m.CreatedBy != "" {
		mi["created by"] = m.CreatedBy
	}
	if m.Encoding != "" {
		mi["encoding"] = m.Encoding
	}
	bencode.Marshal(w, mi)
	return
}
开发者ID:ninive,项目名称:Taipei-Torrent,代码行数:29,代码来源:metainfo.go

示例5: Announce

// Announce announces using HTTP format
func (h HTTPTracker) Announce(query url.Values, file data.FileRecord) []byte {
	// Generate response struct
	announce := AnnounceResponse{
		Interval:    common.Static.Config.Interval,
		MinInterval: common.Static.Config.Interval / 2,
	}

	// Get seeders count on file
	var err error
	announce.Complete, err = file.Seeders()
	if err != nil {
		log.Println(err.Error())
	}

	// Get leechers count on file
	announce.Incomplete, err = file.Leechers()
	if err != nil {
		log.Println(err.Error())
	}

	// Check for numwant parameter, return up to that number of peers
	// Default is 50 per protocol
	numwant := 50
	if query.Get("numwant") != "" {
		// Verify numwant is an integer
		num, err := strconv.Atoi(query.Get("numwant"))
		if err == nil {
			numwant = num
		}
	}

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, announce); err != nil {
		log.Println(err.Error())
		return h.Error(ErrAnnounceFailure.Error())
	}

	// Generate compact peer list of length numwant
	// Note: because we are HTTP, we can mark second parameter as 'true' to get a
	// more accurate peer list
	compactPeers, err := file.CompactPeerList(numwant, true)
	if err != nil {
		log.Println(err.Error())
		return h.Error(ErrPeerListFailure.Error())
	}

	// Because the bencode marshaler does not handle compact, binary peer list conversion,
	// we handle it manually here.

	// Get initial buffer, chop off 3 bytes: "0:e", append the actual list length with new colon
	out := buf.Bytes()
	out = append(out[0:len(out)-3], []byte(strconv.Itoa(len(compactPeers))+":")...)

	// Append peers list, terminate with an "e"
	return append(append(out, compactPeers...), byte('e'))
}
开发者ID:gernest,项目名称:goat,代码行数:58,代码来源:httpTracker.go

示例6: sendMsg

// sendMsg bencodes the data in 'query' and sends it to the remote node.
func sendMsg(conn *net.UDPConn, raddr *net.UDPAddr, query interface{}) {
	totalSent.Add(1)
	var b bytes.Buffer
	if err := bencode.Marshal(&b, query); err != nil {
		return
	}
	if _, err := conn.WriteToUDP(b.Bytes(), raddr); err != nil {
		// debug.Println("DHT: node write failed:", err)
	}
	return
}
开发者ID:screscent,项目名称:dht,代码行数:12,代码来源:krpc.go

示例7: handleScrape

func (t *Tracker) handleScrape(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	infoHashes := r.URL.Query()["info_hash"]
	response := make(bmap)
	response["files"] = t.t.scrape(infoHashes)
	var b bytes.Buffer
	err := bencode.Marshal(&b, response)
	if err == nil {
		w.Write(b.Bytes())
	}
}
开发者ID:nictuku,项目名称:Taipei-Torrent,代码行数:11,代码来源:tracker.go

示例8: createPing

func (s *share) createPing(secret string) []byte {
	buf := bytes.NewBuffer([]byte("DBIT"))
	err := bencode.Marshal(buf, Header{
		"ping",
		*port,
		fmt.Sprintf("%s", sha1.Sum([]byte(secret))),
		fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))),
	})
	check(err)

	return buf.Bytes()
}
开发者ID:rdallman,项目名称:dropbit,代码行数:12,代码来源:share.go

示例9: httpTrackerAnnounce

// httpTrackerAnnounce announces using HTTP format
func httpTrackerAnnounce(query url.Values, file fileRecord, fileUser fileUserRecord) []byte {
	// Generate response struct
	announce := announceResponse{
		Complete:   file.Seeders(),
		Incomplete: file.Leechers(),
	}

	// If client has not yet completed torrent, ask them to announce more frequently, so they can gather
	// more peers and quickly report their statistics
	if fileUser.Completed == false {
		announce.Interval = 600
		announce.MinInterval = 300
	} else {
		// Once a torrent has been completed, report statistics less frequently
		announce.Interval = randRange(static.Config.Interval-600, static.Config.Interval)
		announce.MinInterval = static.Config.Interval / 2
	}

	// Check for numwant parameter, return up to that number of peers
	// Default is 50 per protocol
	numwant := 50
	if query.Get("numwant") != "" {
		// Verify numwant is an integer
		num, err := strconv.Atoi(query.Get("numwant"))
		if err == nil {
			numwant = num
		}
	}

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, announce); err != nil {
		log.Println(err.Error())
		return httpTrackerError("Tracker error: failed to create announce response")
	}

	// Generate compact peer list of length numwant, exclude this user
	peers := file.PeerList(query.Get("ip"), numwant)

	// Because the bencode marshaler does not handle compact, binary peer list conversion,
	// we handle it manually here.

	// Get initial buffer, chop off 3 bytes: "0:e", append the actual list length with new colon
	out := buf.Bytes()
	out = append(out[0:len(out)-3], []byte(strconv.Itoa(len(peers))+":")...)

	// Append peers list, terminate with an "e"
	out = append(append(out, peers...), byte('e'))

	// Return final announce message
	return out
}
开发者ID:ChimeraCoder,项目名称:goat,代码行数:53,代码来源:tracker.go

示例10: handleAnnounce

func (t *Tracker) handleAnnounce(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	response := make(bmap)
	var params announceParams
	var peerListenAddress *net.TCPAddr
	err := params.parse(r.URL)
	if err == nil {
		if params.trackerID != "" && params.trackerID != t.ID {
			err = fmt.Errorf("Incorrect tracker ID: %#v", params.trackerID)
		}
	}
	if err == nil {
		peerListenAddress, err = newTrackerPeerListenAddress(r.RemoteAddr, &params)
	}
	if err == nil {
		now := time.Now()
		t.m.Lock()
		err = t.t.handleAnnounce(now, peerListenAddress, &params, response)
		t.m.Unlock()
		if err == nil {
			response["interval"] = int64(30 * 60)
			response["tracker id"] = t.ID
		}
	}
	var b bytes.Buffer
	if err != nil {
		log.Printf("announce from %v failed: %#v", r.RemoteAddr, err.Error())
		errorResponse := make(bmap)
		errorResponse["failure reason"] = err.Error()
		err = bencode.Marshal(&b, errorResponse)
	} else {
		err = bencode.Marshal(&b, response)
	}
	if err == nil {
		w.Write(b.Bytes())
	}
}
开发者ID:nictuku,项目名称:Taipei-Torrent,代码行数:37,代码来源:tracker.go

示例11: createPiece

func (s *share) createPiece(path string, index, begin int, piece []byte) []byte {
	b := bytes.NewBuffer([]byte("DBIT"))
	err := bencode.Marshal(b, Piece{
		"piece",
		*port,
		fmt.Sprintf("%s", sha1.Sum([]byte(s.Secret))),
		fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))),
		path,
		index,
		begin,
		fmt.Sprintf("%s", piece),
	})
	check(err)
	return b.Bytes()
}
开发者ID:rdallman,项目名称:dropbit,代码行数:15,代码来源:share.go

示例12: createRequest

func (s *share) createRequest(path string, index, begin, length int) []byte {
	b := bytes.NewBuffer([]byte("DBIT"))
	err := bencode.Marshal(b, Request{
		"req",
		*port,
		fmt.Sprintf("%s", sha1.Sum([]byte(s.Secret))),
		fmt.Sprintf("%s", sha1.Sum([]byte("192.168.1.64:6667"))),
		path,
		index,
		begin,
		length,
	})
	check(err)
	return b.Bytes()
}
开发者ID:rdallman,项目名称:dropbit,代码行数:15,代码来源:share.go

示例13: UpdateInfoHash

// Updates the InfoHash field. Call this after manually changing the Info data.
func (m *MetaInfo) UpdateInfoHash(metaInfo *MetaInfo) (err error) {
	var b bytes.Buffer
	infoMap := m.Info.toMap()
	if len(infoMap) > 0 {
		err = bencode.Marshal(&b, infoMap)
		if err != nil {
			return
		}
	}
	hash := sha1.New()
	hash.Write(b.Bytes())

	m.InfoHash = string(hash.Sum(nil))
	return
}
开发者ID:ninive,项目名称:Taipei-Torrent,代码行数:16,代码来源:metainfo.go

示例14: Error

// Error reports a bencoded []byte response as specified by input string
func (h HTTPTracker) Error(err string) []byte {
	res := errorResponse{
		FailureReason: err,
		Interval:      common.Static.Config.Interval,
		MinInterval:   common.Static.Config.Interval / 2,
	}

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, res); err != nil {
		log.Println(err.Error())
		return nil
	}

	return buf.Bytes()
}
开发者ID:sdgoij,项目名称:goat,代码行数:17,代码来源:httpTracker.go

示例15: Announce

// Announce announces using HTTP format
func (h HTTPTracker) Announce(query url.Values, file data.FileRecord) []byte {
	// Generate response struct
	announce := AnnounceResponse{
		Complete:    file.Seeders(),
		Incomplete:  file.Leechers(),
		Interval:    common.Static.Config.Interval,
		MinInterval: common.Static.Config.Interval / 2,
	}

	// Check for numwant parameter, return up to that number of peers
	// Default is 50 per protocol
	numwant := 50
	if query.Get("numwant") != "" {
		// Verify numwant is an integer
		num, err := strconv.Atoi(query.Get("numwant"))
		if err == nil {
			numwant = num
		}
	}

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, announce); err != nil {
		log.Println(err.Error())
		return h.Error("Tracker error: failed to create announce response")
	}

	// Generate compact peer list of length numwant, exclude this user
	peers := file.PeerList(query.Get("ip"), numwant)

	// Because the bencode marshaler does not handle compact, binary peer list conversion,
	// we handle it manually here.

	// Get initial buffer, chop off 3 bytes: "0:e", append the actual list length with new colon
	out := buf.Bytes()
	out = append(out[0:len(out)-3], []byte(strconv.Itoa(len(peers))+":")...)

	// Append peers list, terminate with an "e"
	out = append(append(out, peers...), byte('e'))

	// Return final announce message
	return out
}
开发者ID:sdgoij,项目名称:goat,代码行数:44,代码来源:httpTracker.go


注:本文中的code/google/com/p/bencode-go.Marshal函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。