本文整理汇总了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()
}
示例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
}
示例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()
}
示例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
}
示例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'))
}
示例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
}
示例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())
}
}
示例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()
}
示例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
}
示例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, ¶ms)
}
if err == nil {
now := time.Now()
t.m.Lock()
err = t.t.handleAnnounce(now, peerListenAddress, ¶ms, 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())
}
}
示例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()
}
示例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()
}
示例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
}
示例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()
}
示例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
}