本文整理汇总了Golang中github.com/zeebo/bencode.NewEncoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewEncoder函数的具体用法?Golang NewEncoder怎么用?Golang NewEncoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewEncoder函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: writeEncoded
func writeEncoded(c appengine.Context, w http.ResponseWriter, data interface{}) {
newEncoder := bencode.NewEncoder(w)
if err := newEncoder.Encode(data); err != nil {
c.Errorf("Failed to encode data: %s", err)
writeInternalError(w)
}
}
示例2: encodeResponseMap
// Bencodes an arbitrary dictionary as a tracker response.
func encodeResponseMap(responseMap map[string]interface{}) io.Reader {
responseBuf := bytes.NewBuffer(make([]byte, 0))
encoder := bencode.NewEncoder(responseBuf)
_ = encoder.Encode(responseMap)
return responseBuf
}
示例3: SendExtensions
func (p *peerState) SendExtensions(supportedExtensions map[int]string,
metadataSize int64) {
handshake := ExtensionHandshake{
M: make(map[string]int, len(supportedExtensions)),
V: "Taipei-Torrent dev",
MetadataSize: metadataSize,
}
for i, ext := range supportedExtensions {
handshake.M[ext] = i
}
var buf bytes.Buffer
err := bencode.NewEncoder(&buf).Encode(handshake)
if err != nil {
log.Println("Error when marshalling extension message")
return
}
msg := make([]byte, 2+buf.Len())
msg[0] = EXTENSION
msg[1] = EXTENSION_HANDSHAKE
copy(msg[2:], buf.Bytes())
p.sendMessage(msg)
}
示例4: ReadTorrent
// 读取种子信息
func ReadTorrent(r io.Reader) (meta MetaInfo, err error) {
// 读取文件信息
s, err := ioutil.ReadAll(r)
if err != nil {
return
}
err = bencode.DecodeBytes(s, &meta)
if err != nil {
return
}
hash := sha1.New()
err = bencode.NewEncoder(hash).Encode(meta.Info)
if err != nil {
return
}
meta.InfoHash = fmt.Sprintf("%02X", string(hash.Sum(nil)))
return
/*var m interface{}
m, err = bencode.Decode(r)
if err != nil {
return
}
topMap, ok := m.(map[string]interface{})
if !ok {
return
}
infoMap, ok := topMap["info"]
if !ok {
return
}
var b bytes.Buffer
if err = bencode.Marshal(&b, infoMap); err != nil {
return
}
hash := sha1.New()
hash.Write(b.Bytes())
err = bencode.Unmarshal(&b, &meta.Info)
if err != nil {
return
}
meta.InfoHash = fmt.Sprintf("%X", string(hash.Sum(nil)))
meta.Announce = getString(topMap, "announce")
meta.Comment = getString(topMap, "comment")
meta.CreatedBy = getString(topMap, "created by")
meta.CreationDate = getInt64(topMap, "creation date")
meta.Encoding = getString(topMap, "encoding")
return*/
}
示例5: MD5Params
// MD5Params returns the MD5 hash of the provided map[string]string.
// This could easily be extended to support hashing any datatype supported
// by bencode.
func MD5Params(val map[string]string) (string, error) {
md5Writer := md5.New()
enc := bencode.NewEncoder(md5Writer)
if err := enc.Encode(val); err != nil {
return "", err
}
return fmt.Sprintf("%x", md5Writer.Sum(nil)), nil
}
示例6: Size
// Returns the size of the representation of this metainfo as a bencoded
// dictionary
func (m *MetaInfo) Size() (sz int) {
var buf bytes.Buffer
err := bencode.NewEncoder(&buf).Encode(m)
if err != nil {
log.Fatal("Couldn't bencode this metainfo: ", err)
}
return buf.Len()
}
示例7: saveToDisk
func (m *MetaInfo) saveToDisk(dir string) (err error) {
ihhex := fmt.Sprintf("%x", m.InfoHash)
f, err := os.Create(filepath.Join(dir, ihhex))
if err != nil {
log.Println("Error when opening file for creation: ", err)
return
}
defer f.Close()
return bencode.NewEncoder(f).Encode(m)
}
示例8: BencodeInfoDict
// Returns a bencoded version of the torrent's info dict.
func (t *TorrentFile) BencodeInfoDict() ([]byte, error) {
infoBuffer := bytes.NewBuffer(make([]byte, 0))
encoder := bencode.NewEncoder(infoBuffer)
err := encoder.Encode(t.Info)
if err != nil {
fmt.Printf("error encoding torrent file: %s", err.Error())
}
return infoBuffer.Bytes(), err
}
示例9: benc
func benc(w http.ResponseWriter, req *http.Request) {
enc := bencode.NewEncoder(w)
if err := enc.Encode(map[string]interface{}{
"foo": "bar",
"baz": 2,
"buf": []string{"baz", "bloof"},
}); err != nil {
log.Println(err)
}
log.Printf("Handled request from %s :)", req.RemoteAddr)
}
示例10: constructArgs
func (query *Query) constructArgs(args interface{}) error {
buf := new(bytes.Buffer)
bencodeE := bencode.NewEncoder(buf)
if err := bencodeE.Encode(args); err != nil {
return err
}
data, err := encodeIntoBigEndian(buf)
query.ProcedureData = data
return err
}
示例11: announceRecover
func announceRecover(w http.ResponseWriter) {
err := recover()
if err == nil {
return
}
w.WriteHeader(http.StatusInternalServerError)
enc := bencode.NewEncoder(w)
enc.Encode(M{"failure reason": err})
//DEBUG: newline for debugging
fmt.Fprintln(w, "")
}
示例12: WriteFile
// Converts torrent to SUPRA-PRIVATE torrent
//
// Sets the private flag to 1 and embeds the supplied secret and hash
// for authentication purposes.
//
// This torrent file SHOULD NOT be shared between users or statistics collection
// and anti-abuse mechanisms will be skewed for that user.
func (t *TorrentFile) WriteFile(secret, hash []byte) ([]byte, error) {
fmt.Printf("writing file...")
t.Announce = fmt.Sprintf("http://tracker.fatalsyntax.com:4200/%s/%s/announce", hex.EncodeToString(secret), hex.EncodeToString(hash))
t.Encoding = "UTF-8"
infoBuffer := bytes.NewBuffer(make([]byte, 0))
encoder := bencode.NewEncoder(infoBuffer)
err := encoder.Encode(t)
if err != nil {
return nil, err
}
return infoBuffer.Bytes(), nil
}
示例13: DoMetadata
func (cs *ControlSession) DoMetadata(msg []byte, p *peerState) (err error) {
var message IHMessage
err = bencode.NewDecoder(bytes.NewReader(msg)).Decode(&message)
if err != nil {
cs.log("Couldn't decode metadata message: ", err)
return
}
if message.Port == 0 {
return
}
// take his IP addr, use the advertised port
ip := p.conn.RemoteAddr().(*net.TCPAddr).IP.String()
port := strconv.Itoa(int(message.Port))
peer := ip + ":" + port
if cs.isNewerThan(message.Info.Rev) {
return
}
var tmpInfoBuf bytes.Buffer
err = bencode.NewEncoder(&tmpInfoBuf).Encode(message.Info)
if err != nil {
cs.log("Couldn't encode ih message, returning now")
return err
}
rawInfo := tmpInfoBuf.Bytes()
pub := [ed.PublicKeySize]byte(cs.ID.Pub)
var sig [ed.SignatureSize]byte
copy(sig[0:ed.SignatureSize], message.Sig)
ok := ed.Verify(&pub, rawInfo, &sig)
if !ok {
return errors.New("Bad Signature")
}
var test IHMessage
err = bencode.NewDecoder(bytes.NewReader(msg)).Decode(&test)
cs.session.SaveIHMessage(msg)
cs.Torrents <- Announce{
infohash: message.Info.InfoHash,
peer: peer,
}
return
}
示例14: EncodeInfo
// Encode's the `info` dictionary into a SHA1 hash; used to uniquely identify a torrent.
func (t *TorrentFile) EncodeInfo() []byte {
//torrentDict := torrentMetainfo.(map[string]interface{})
infoBytes := make([]byte, 0) //TODO: intelligenty size buffer based on info
infoBuffer := bytes.NewBuffer(infoBytes)
encoder := bencode.NewEncoder(infoBuffer)
err := encoder.Encode(t.Info)
if err != nil {
fmt.Printf("error encoding torrent file: %s", err.Error())
}
hash := sha1.New()
io.Copy(hash, infoBuffer)
return hash.Sum(nil)
}
示例15: RawInfo
// Returns the representation of this metainfo's info dict as a
// bencoded dictionary
func (m *MetaInfo) RawInfo() (b []byte) {
if m.rawInfo != nil {
return m.rawInfo
}
if m.Info == nil {
return []byte{}
}
var buf bytes.Buffer
err := bencode.NewEncoder(&buf).Encode(m.Info)
if err != nil {
log.Fatal("Couldn't bencode this metainfo's dict: ", err)
}
m.rawInfo = buf.Bytes()
return m.rawInfo
}