repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
allegro/bigcache
server/middleware.go
requestMetrics
func requestMetrics(l *log.Logger) service { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() h.ServeHTTP(w, r) l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds()) }) } }
go
func requestMetrics(l *log.Logger) service { return func(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { start := time.Now() h.ServeHTTP(w, r) l.Printf("%s request to %s took %vns.", r.Method, r.URL.Path, time.Now().Sub(start).Nanoseconds()) }) } }
[ "func", "requestMetrics", "(", "l", "*", "log", ".", "Logger", ")", "service", "{", "return", "func", "(", "h", "http", ".", "Handler", ")", "http", ".", "Handler", "{", "return", "http", ".", "HandlerFunc", "(", "func", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "start", ":=", "time", ".", "Now", "(", ")", "\n", "h", ".", "ServeHTTP", "(", "w", ",", "r", ")", "\n", "l", ".", "Printf", "(", "\"%s request to %s took %vns.\"", ",", "r", ".", "Method", ",", "r", ".", "URL", ".", "Path", ",", "time", ".", "Now", "(", ")", ".", "Sub", "(", "start", ")", ".", "Nanoseconds", "(", ")", ")", "\n", "}", ")", "\n", "}", "\n", "}" ]
// middleware for request length metrics.
[ "middleware", "for", "request", "length", "metrics", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/middleware.go#L21-L29
train
allegro/bigcache
iterator.go
SetNext
func (it *EntryInfoIterator) SetNext() bool { it.mutex.Lock() it.valid = false it.currentIndex++ if it.elementsCount > it.currentIndex { it.valid = true it.mutex.Unlock() return true } for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { it.elements, it.elementsCount = it.cache.shards[i].copyKeys() // Non empty shard - stick with it if it.elementsCount > 0 { it.currentIndex = 0 it.currentShard = i it.valid = true it.mutex.Unlock() return true } } it.mutex.Unlock() return false }
go
func (it *EntryInfoIterator) SetNext() bool { it.mutex.Lock() it.valid = false it.currentIndex++ if it.elementsCount > it.currentIndex { it.valid = true it.mutex.Unlock() return true } for i := it.currentShard + 1; i < it.cache.config.Shards; i++ { it.elements, it.elementsCount = it.cache.shards[i].copyKeys() // Non empty shard - stick with it if it.elementsCount > 0 { it.currentIndex = 0 it.currentShard = i it.valid = true it.mutex.Unlock() return true } } it.mutex.Unlock() return false }
[ "func", "(", "it", "*", "EntryInfoIterator", ")", "SetNext", "(", ")", "bool", "{", "it", ".", "mutex", ".", "Lock", "(", ")", "\n", "it", ".", "valid", "=", "false", "\n", "it", ".", "currentIndex", "++", "\n", "if", "it", ".", "elementsCount", ">", "it", ".", "currentIndex", "{", "it", ".", "valid", "=", "true", "\n", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}", "\n", "for", "i", ":=", "it", ".", "currentShard", "+", "1", ";", "i", "<", "it", ".", "cache", ".", "config", ".", "Shards", ";", "i", "++", "{", "it", ".", "elements", ",", "it", ".", "elementsCount", "=", "it", ".", "cache", ".", "shards", "[", "i", "]", ".", "copyKeys", "(", ")", "\n", "if", "it", ".", "elementsCount", ">", "0", "{", "it", ".", "currentIndex", "=", "0", "\n", "it", ".", "currentShard", "=", "i", "\n", "it", ".", "valid", "=", "true", "\n", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "false", "\n", "}" ]
// SetNext moves to next element and returns true if it exists.
[ "SetNext", "moves", "to", "next", "element", "and", "returns", "true", "if", "it", "exists", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/iterator.go#L59-L85
train
allegro/bigcache
iterator.go
Value
func (it *EntryInfoIterator) Value() (EntryInfo, error) { it.mutex.Lock() if !it.valid { it.mutex.Unlock() return emptyEntryInfo, ErrInvalidIteratorState } entry, err := it.cache.shards[it.currentShard].getEntry(int(it.elements[it.currentIndex])) if err != nil { it.mutex.Unlock() return emptyEntryInfo, ErrCannotRetrieveEntry } it.mutex.Unlock() return EntryInfo{ timestamp: readTimestampFromEntry(entry), hash: readHashFromEntry(entry), key: readKeyFromEntry(entry), value: readEntry(entry), }, nil }
go
func (it *EntryInfoIterator) Value() (EntryInfo, error) { it.mutex.Lock() if !it.valid { it.mutex.Unlock() return emptyEntryInfo, ErrInvalidIteratorState } entry, err := it.cache.shards[it.currentShard].getEntry(int(it.elements[it.currentIndex])) if err != nil { it.mutex.Unlock() return emptyEntryInfo, ErrCannotRetrieveEntry } it.mutex.Unlock() return EntryInfo{ timestamp: readTimestampFromEntry(entry), hash: readHashFromEntry(entry), key: readKeyFromEntry(entry), value: readEntry(entry), }, nil }
[ "func", "(", "it", "*", "EntryInfoIterator", ")", "Value", "(", ")", "(", "EntryInfo", ",", "error", ")", "{", "it", ".", "mutex", ".", "Lock", "(", ")", "\n", "if", "!", "it", ".", "valid", "{", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "emptyEntryInfo", ",", "ErrInvalidIteratorState", "\n", "}", "\n", "entry", ",", "err", ":=", "it", ".", "cache", ".", "shards", "[", "it", ".", "currentShard", "]", ".", "getEntry", "(", "int", "(", "it", ".", "elements", "[", "it", ".", "currentIndex", "]", ")", ")", "\n", "if", "err", "!=", "nil", "{", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "emptyEntryInfo", ",", "ErrCannotRetrieveEntry", "\n", "}", "\n", "it", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "EntryInfo", "{", "timestamp", ":", "readTimestampFromEntry", "(", "entry", ")", ",", "hash", ":", "readHashFromEntry", "(", "entry", ")", ",", "key", ":", "readKeyFromEntry", "(", "entry", ")", ",", "value", ":", "readEntry", "(", "entry", ")", ",", "}", ",", "nil", "\n", "}" ]
// Value returns current value from the iterator
[ "Value", "returns", "current", "value", "from", "the", "iterator" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/iterator.go#L100-L122
train
allegro/bigcache
server/cache_handlers.go
getCacheHandler
func getCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if target == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("can't get a key if there is no key.")) log.Print("empty request.") return } entry, err := cache.Get(target) if err != nil { errMsg := (err).Error() if strings.Contains(errMsg, "not found") { log.Print(err) w.WriteHeader(http.StatusNotFound) return } log.Print(err) w.WriteHeader(http.StatusInternalServerError) return } w.Write(entry) }
go
func getCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if target == "" { w.WriteHeader(http.StatusBadRequest) w.Write([]byte("can't get a key if there is no key.")) log.Print("empty request.") return } entry, err := cache.Get(target) if err != nil { errMsg := (err).Error() if strings.Contains(errMsg, "not found") { log.Print(err) w.WriteHeader(http.StatusNotFound) return } log.Print(err) w.WriteHeader(http.StatusInternalServerError) return } w.Write(entry) }
[ "func", "getCacheHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "target", ":=", "r", ".", "URL", ".", "Path", "[", "len", "(", "cachePath", ")", ":", "]", "\n", "if", "target", "==", "\"\"", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusBadRequest", ")", "\n", "w", ".", "Write", "(", "[", "]", "byte", "(", "\"can't get a key if there is no key.\"", ")", ")", "\n", "log", ".", "Print", "(", "\"empty request.\"", ")", "\n", "return", "\n", "}", "\n", "entry", ",", "err", ":=", "cache", ".", "Get", "(", "target", ")", "\n", "if", "err", "!=", "nil", "{", "errMsg", ":=", "(", "err", ")", ".", "Error", "(", ")", "\n", "if", "strings", ".", "Contains", "(", "errMsg", ",", "\"not found\"", ")", "{", "log", ".", "Print", "(", "err", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "return", "\n", "}", "\n", "log", ".", "Print", "(", "err", ")", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "return", "\n", "}", "\n", "w", ".", "Write", "(", "entry", ")", "\n", "}" ]
// handles get requests.
[ "handles", "get", "requests", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/cache_handlers.go#L24-L45
train
allegro/bigcache
server/cache_handlers.go
deleteCacheHandler
func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if err := cache.Delete(target); err != nil { if strings.Contains((err).Error(), "not found") { w.WriteHeader(http.StatusNotFound) log.Printf("%s not found.", target) return } w.WriteHeader(http.StatusInternalServerError) log.Printf("internal cache error: %s", err) } // this is what the RFC says to use when calling DELETE. w.WriteHeader(http.StatusOK) return }
go
func deleteCacheHandler(w http.ResponseWriter, r *http.Request) { target := r.URL.Path[len(cachePath):] if err := cache.Delete(target); err != nil { if strings.Contains((err).Error(), "not found") { w.WriteHeader(http.StatusNotFound) log.Printf("%s not found.", target) return } w.WriteHeader(http.StatusInternalServerError) log.Printf("internal cache error: %s", err) } // this is what the RFC says to use when calling DELETE. w.WriteHeader(http.StatusOK) return }
[ "func", "deleteCacheHandler", "(", "w", "http", ".", "ResponseWriter", ",", "r", "*", "http", ".", "Request", ")", "{", "target", ":=", "r", ".", "URL", ".", "Path", "[", "len", "(", "cachePath", ")", ":", "]", "\n", "if", "err", ":=", "cache", ".", "Delete", "(", "target", ")", ";", "err", "!=", "nil", "{", "if", "strings", ".", "Contains", "(", "(", "err", ")", ".", "Error", "(", ")", ",", "\"not found\"", ")", "{", "w", ".", "WriteHeader", "(", "http", ".", "StatusNotFound", ")", "\n", "log", ".", "Printf", "(", "\"%s not found.\"", ",", "target", ")", "\n", "return", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusInternalServerError", ")", "\n", "log", ".", "Printf", "(", "\"internal cache error: %s\"", ",", "err", ")", "\n", "}", "\n", "w", ".", "WriteHeader", "(", "http", ".", "StatusOK", ")", "\n", "return", "\n", "}" ]
// delete cache objects.
[ "delete", "cache", "objects", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/server/cache_handlers.go#L73-L87
train
allegro/bigcache
fnv.go
Sum64
func (f fnv64a) Sum64(key string) uint64 { var hash uint64 = offset64 for i := 0; i < len(key); i++ { hash ^= uint64(key[i]) hash *= prime64 } return hash }
go
func (f fnv64a) Sum64(key string) uint64 { var hash uint64 = offset64 for i := 0; i < len(key); i++ { hash ^= uint64(key[i]) hash *= prime64 } return hash }
[ "func", "(", "f", "fnv64a", ")", "Sum64", "(", "key", "string", ")", "uint64", "{", "var", "hash", "uint64", "=", "offset64", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "key", ")", ";", "i", "++", "{", "hash", "^=", "uint64", "(", "key", "[", "i", "]", ")", "\n", "hash", "*=", "prime64", "\n", "}", "\n", "return", "hash", "\n", "}" ]
// Sum64 gets the string and returns its uint64 hash value.
[ "Sum64", "gets", "the", "string", "and", "returns", "its", "uint64", "hash", "value", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/fnv.go#L20-L28
train
allegro/bigcache
queue/bytes_queue.go
NewBytesQueue
func NewBytesQueue(initialCapacity int, maxCapacity int, verbose bool) *BytesQueue { return &BytesQueue{ array: make([]byte, initialCapacity), capacity: initialCapacity, maxCapacity: maxCapacity, headerBuffer: make([]byte, headerEntrySize), tail: leftMarginIndex, head: leftMarginIndex, rightMargin: leftMarginIndex, verbose: verbose, initialCapacity: initialCapacity, } }
go
func NewBytesQueue(initialCapacity int, maxCapacity int, verbose bool) *BytesQueue { return &BytesQueue{ array: make([]byte, initialCapacity), capacity: initialCapacity, maxCapacity: maxCapacity, headerBuffer: make([]byte, headerEntrySize), tail: leftMarginIndex, head: leftMarginIndex, rightMargin: leftMarginIndex, verbose: verbose, initialCapacity: initialCapacity, } }
[ "func", "NewBytesQueue", "(", "initialCapacity", "int", ",", "maxCapacity", "int", ",", "verbose", "bool", ")", "*", "BytesQueue", "{", "return", "&", "BytesQueue", "{", "array", ":", "make", "(", "[", "]", "byte", ",", "initialCapacity", ")", ",", "capacity", ":", "initialCapacity", ",", "maxCapacity", ":", "maxCapacity", ",", "headerBuffer", ":", "make", "(", "[", "]", "byte", ",", "headerEntrySize", ")", ",", "tail", ":", "leftMarginIndex", ",", "head", ":", "leftMarginIndex", ",", "rightMargin", ":", "leftMarginIndex", ",", "verbose", ":", "verbose", ",", "initialCapacity", ":", "initialCapacity", ",", "}", "\n", "}" ]
// NewBytesQueue initialize new bytes queue. // Initial capacity is used in bytes array allocation // When verbose flag is set then information about memory allocation are printed
[ "NewBytesQueue", "initialize", "new", "bytes", "queue", ".", "Initial", "capacity", "is", "used", "in", "bytes", "array", "allocation", "When", "verbose", "flag", "is", "set", "then", "information", "about", "memory", "allocation", "are", "printed" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L47-L59
train
allegro/bigcache
queue/bytes_queue.go
Reset
func (q *BytesQueue) Reset() { // Just reset indexes q.tail = leftMarginIndex q.head = leftMarginIndex q.rightMargin = leftMarginIndex q.count = 0 }
go
func (q *BytesQueue) Reset() { // Just reset indexes q.tail = leftMarginIndex q.head = leftMarginIndex q.rightMargin = leftMarginIndex q.count = 0 }
[ "func", "(", "q", "*", "BytesQueue", ")", "Reset", "(", ")", "{", "q", ".", "tail", "=", "leftMarginIndex", "\n", "q", ".", "head", "=", "leftMarginIndex", "\n", "q", ".", "rightMargin", "=", "leftMarginIndex", "\n", "q", ".", "count", "=", "0", "\n", "}" ]
// Reset removes all entries from queue
[ "Reset", "removes", "all", "entries", "from", "queue" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L62-L68
train
allegro/bigcache
queue/bytes_queue.go
Push
func (q *BytesQueue) Push(data []byte) (int, error) { dataLen := len(data) if q.availableSpaceAfterTail() < dataLen+headerEntrySize { if q.availableSpaceBeforeHead() >= dataLen+headerEntrySize { q.tail = leftMarginIndex } else if q.capacity+headerEntrySize+dataLen >= q.maxCapacity && q.maxCapacity > 0 { return -1, &queueError{"Full queue. Maximum size limit reached."} } else { q.allocateAdditionalMemory(dataLen + headerEntrySize) } } index := q.tail q.push(data, dataLen) return index, nil }
go
func (q *BytesQueue) Push(data []byte) (int, error) { dataLen := len(data) if q.availableSpaceAfterTail() < dataLen+headerEntrySize { if q.availableSpaceBeforeHead() >= dataLen+headerEntrySize { q.tail = leftMarginIndex } else if q.capacity+headerEntrySize+dataLen >= q.maxCapacity && q.maxCapacity > 0 { return -1, &queueError{"Full queue. Maximum size limit reached."} } else { q.allocateAdditionalMemory(dataLen + headerEntrySize) } } index := q.tail q.push(data, dataLen) return index, nil }
[ "func", "(", "q", "*", "BytesQueue", ")", "Push", "(", "data", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "dataLen", ":=", "len", "(", "data", ")", "\n", "if", "q", ".", "availableSpaceAfterTail", "(", ")", "<", "dataLen", "+", "headerEntrySize", "{", "if", "q", ".", "availableSpaceBeforeHead", "(", ")", ">=", "dataLen", "+", "headerEntrySize", "{", "q", ".", "tail", "=", "leftMarginIndex", "\n", "}", "else", "if", "q", ".", "capacity", "+", "headerEntrySize", "+", "dataLen", ">=", "q", ".", "maxCapacity", "&&", "q", ".", "maxCapacity", ">", "0", "{", "return", "-", "1", ",", "&", "queueError", "{", "\"Full queue. Maximum size limit reached.\"", "}", "\n", "}", "else", "{", "q", ".", "allocateAdditionalMemory", "(", "dataLen", "+", "headerEntrySize", ")", "\n", "}", "\n", "}", "\n", "index", ":=", "q", ".", "tail", "\n", "q", ".", "push", "(", "data", ",", "dataLen", ")", "\n", "return", "index", ",", "nil", "\n", "}" ]
// Push copies entry at the end of queue and moves tail pointer. Allocates more space if needed. // Returns index for pushed data or error if maximum size queue limit is reached.
[ "Push", "copies", "entry", "at", "the", "end", "of", "queue", "and", "moves", "tail", "pointer", ".", "Allocates", "more", "space", "if", "needed", ".", "Returns", "index", "for", "pushed", "data", "or", "error", "if", "maximum", "size", "queue", "limit", "is", "reached", "." ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L72-L90
train
allegro/bigcache
queue/bytes_queue.go
Pop
func (q *BytesQueue) Pop() ([]byte, error) { data, size, err := q.peek(q.head) if err != nil { return nil, err } q.head += headerEntrySize + size q.count-- if q.head == q.rightMargin { q.head = leftMarginIndex if q.tail == q.rightMargin { q.tail = leftMarginIndex } q.rightMargin = q.tail } return data, nil }
go
func (q *BytesQueue) Pop() ([]byte, error) { data, size, err := q.peek(q.head) if err != nil { return nil, err } q.head += headerEntrySize + size q.count-- if q.head == q.rightMargin { q.head = leftMarginIndex if q.tail == q.rightMargin { q.tail = leftMarginIndex } q.rightMargin = q.tail } return data, nil }
[ "func", "(", "q", "*", "BytesQueue", ")", "Pop", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "size", ",", "err", ":=", "q", ".", "peek", "(", "q", ".", "head", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "q", ".", "head", "+=", "headerEntrySize", "+", "size", "\n", "q", ".", "count", "--", "\n", "if", "q", ".", "head", "==", "q", ".", "rightMargin", "{", "q", ".", "head", "=", "leftMarginIndex", "\n", "if", "q", ".", "tail", "==", "q", ".", "rightMargin", "{", "q", ".", "tail", "=", "leftMarginIndex", "\n", "}", "\n", "q", ".", "rightMargin", "=", "q", ".", "tail", "\n", "}", "\n", "return", "data", ",", "nil", "\n", "}" ]
// Pop reads the oldest entry from queue and moves head pointer to the next one
[ "Pop", "reads", "the", "oldest", "entry", "from", "queue", "and", "moves", "head", "pointer", "to", "the", "next", "one" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L139-L157
train
allegro/bigcache
queue/bytes_queue.go
Peek
func (q *BytesQueue) Peek() ([]byte, error) { data, _, err := q.peek(q.head) return data, err }
go
func (q *BytesQueue) Peek() ([]byte, error) { data, _, err := q.peek(q.head) return data, err }
[ "func", "(", "q", "*", "BytesQueue", ")", "Peek", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "_", ",", "err", ":=", "q", ".", "peek", "(", "q", ".", "head", ")", "\n", "return", "data", ",", "err", "\n", "}" ]
// Peek reads the oldest entry from list without moving head pointer
[ "Peek", "reads", "the", "oldest", "entry", "from", "list", "without", "moving", "head", "pointer" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L160-L163
train
allegro/bigcache
queue/bytes_queue.go
Get
func (q *BytesQueue) Get(index int) ([]byte, error) { data, _, err := q.peek(index) return data, err }
go
func (q *BytesQueue) Get(index int) ([]byte, error) { data, _, err := q.peek(index) return data, err }
[ "func", "(", "q", "*", "BytesQueue", ")", "Get", "(", "index", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "data", ",", "_", ",", "err", ":=", "q", ".", "peek", "(", "index", ")", "\n", "return", "data", ",", "err", "\n", "}" ]
// Get reads entry from index
[ "Get", "reads", "entry", "from", "index" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L166-L169
train
allegro/bigcache
queue/bytes_queue.go
peekCheckErr
func (q *BytesQueue) peekCheckErr(index int) error { if q.count == 0 { return errEmptyQueue } if index <= 0 { return errInvalidIndex } if index+headerEntrySize >= len(q.array) { return errIndexOutOfBounds } return nil }
go
func (q *BytesQueue) peekCheckErr(index int) error { if q.count == 0 { return errEmptyQueue } if index <= 0 { return errInvalidIndex } if index+headerEntrySize >= len(q.array) { return errIndexOutOfBounds } return nil }
[ "func", "(", "q", "*", "BytesQueue", ")", "peekCheckErr", "(", "index", "int", ")", "error", "{", "if", "q", ".", "count", "==", "0", "{", "return", "errEmptyQueue", "\n", "}", "\n", "if", "index", "<=", "0", "{", "return", "errInvalidIndex", "\n", "}", "\n", "if", "index", "+", "headerEntrySize", ">=", "len", "(", "q", ".", "array", ")", "{", "return", "errIndexOutOfBounds", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// peekCheckErr is identical to peek, but does not actually return any data
[ "peekCheckErr", "is", "identical", "to", "peek", "but", "does", "not", "actually", "return", "any", "data" ]
e24eb225f15679bbe54f91bfa7da3b00e59b9768
https://github.com/allegro/bigcache/blob/e24eb225f15679bbe54f91bfa7da3b00e59b9768/queue/bytes_queue.go#L192-L206
train
sevlyar/go-daemon
examples/cmd/gd-log-rotation/log_file.go
NewLogFile
func NewLogFile(name string, file *os.File) (*LogFile, error) { rw := &LogFile{ file: file, name: name, } if file == nil { if err := rw.Rotate(); err != nil { return nil, err } } return rw, nil }
go
func NewLogFile(name string, file *os.File) (*LogFile, error) { rw := &LogFile{ file: file, name: name, } if file == nil { if err := rw.Rotate(); err != nil { return nil, err } } return rw, nil }
[ "func", "NewLogFile", "(", "name", "string", ",", "file", "*", "os", ".", "File", ")", "(", "*", "LogFile", ",", "error", ")", "{", "rw", ":=", "&", "LogFile", "{", "file", ":", "file", ",", "name", ":", "name", ",", "}", "\n", "if", "file", "==", "nil", "{", "if", "err", ":=", "rw", ".", "Rotate", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "rw", ",", "nil", "\n", "}" ]
// NewLogFile creates a new LogFile. The file is optional - it will be created if needed.
[ "NewLogFile", "creates", "a", "new", "LogFile", ".", "The", "file", "is", "optional", "-", "it", "will", "be", "created", "if", "needed", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/examples/cmd/gd-log-rotation/log_file.go#L16-L27
train
sevlyar/go-daemon
examples/cmd/gd-log-rotation/log_file.go
Rotate
func (l *LogFile) Rotate() error { // rename dest file if it already exists. if _, err := os.Stat(l.name); err == nil { name := l.name + "." + time.Now().Format(time.RFC3339) if err = os.Rename(l.name, name); err != nil { return err } } // create new file. file, err := os.Create(l.name) if err != nil { return err } // switch dest file safely. l.mu.Lock() file, l.file = l.file, file l.mu.Unlock() // close old file if open. if file != nil { if err := file.Close(); err != nil { return err } } return nil }
go
func (l *LogFile) Rotate() error { // rename dest file if it already exists. if _, err := os.Stat(l.name); err == nil { name := l.name + "." + time.Now().Format(time.RFC3339) if err = os.Rename(l.name, name); err != nil { return err } } // create new file. file, err := os.Create(l.name) if err != nil { return err } // switch dest file safely. l.mu.Lock() file, l.file = l.file, file l.mu.Unlock() // close old file if open. if file != nil { if err := file.Close(); err != nil { return err } } return nil }
[ "func", "(", "l", "*", "LogFile", ")", "Rotate", "(", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "l", ".", "name", ")", ";", "err", "==", "nil", "{", "name", ":=", "l", ".", "name", "+", "\".\"", "+", "time", ".", "Now", "(", ")", ".", "Format", "(", "time", ".", "RFC3339", ")", "\n", "if", "err", "=", "os", ".", "Rename", "(", "l", ".", "name", ",", "name", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "Create", "(", "l", ".", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "l", ".", "mu", ".", "Lock", "(", ")", "\n", "file", ",", "l", ".", "file", "=", "l", ".", "file", ",", "file", "\n", "l", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "file", "!=", "nil", "{", "if", "err", ":=", "file", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Rotate renames old log file, creates new one, switches log and closes the old file.
[ "Rotate", "renames", "old", "log", "file", "creates", "new", "one", "switches", "log", "and", "closes", "the", "old", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/examples/cmd/gd-log-rotation/log_file.go#L37-L61
train
sevlyar/go-daemon
lock_file.go
CreatePidFile
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) { if lock, err = OpenLockFile(name, perm); err != nil { return } if err = lock.Lock(); err != nil { lock.Remove() return } if err = lock.WritePid(); err != nil { lock.Remove() } return }
go
func CreatePidFile(name string, perm os.FileMode) (lock *LockFile, err error) { if lock, err = OpenLockFile(name, perm); err != nil { return } if err = lock.Lock(); err != nil { lock.Remove() return } if err = lock.WritePid(); err != nil { lock.Remove() } return }
[ "func", "CreatePidFile", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "(", "lock", "*", "LockFile", ",", "err", "error", ")", "{", "if", "lock", ",", "err", "=", "OpenLockFile", "(", "name", ",", "perm", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "lock", ".", "Lock", "(", ")", ";", "err", "!=", "nil", "{", "lock", ".", "Remove", "(", ")", "\n", "return", "\n", "}", "\n", "if", "err", "=", "lock", ".", "WritePid", "(", ")", ";", "err", "!=", "nil", "{", "lock", ".", "Remove", "(", ")", "\n", "}", "\n", "return", "\n", "}" ]
// CreatePidFile opens the named file, applies exclusive lock and writes // current process id to file.
[ "CreatePidFile", "opens", "the", "named", "file", "applies", "exclusive", "lock", "and", "writes", "current", "process", "id", "to", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L26-L38
train
sevlyar/go-daemon
lock_file.go
OpenLockFile
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil { lock = &LockFile{file} } return }
go
func OpenLockFile(name string, perm os.FileMode) (lock *LockFile, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, perm); err == nil { lock = &LockFile{file} } return }
[ "func", "OpenLockFile", "(", "name", "string", ",", "perm", "os", ".", "FileMode", ")", "(", "lock", "*", "LockFile", ",", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "if", "file", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_RDWR", "|", "os", ".", "O_CREATE", ",", "perm", ")", ";", "err", "==", "nil", "{", "lock", "=", "&", "LockFile", "{", "file", "}", "\n", "}", "\n", "return", "\n", "}" ]
// OpenLockFile opens the named file with flags os.O_RDWR|os.O_CREATE and specified perm. // If successful, function returns LockFile for opened file.
[ "OpenLockFile", "opens", "the", "named", "file", "with", "flags", "os", ".", "O_RDWR|os", ".", "O_CREATE", "and", "specified", "perm", ".", "If", "successful", "function", "returns", "LockFile", "for", "opened", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L42-L48
train
sevlyar/go-daemon
lock_file.go
ReadPidFile
func ReadPidFile(name string) (pid int, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil { return } defer file.Close() lock := &LockFile{file} pid, err = lock.ReadPid() return }
go
func ReadPidFile(name string) (pid int, err error) { var file *os.File if file, err = os.OpenFile(name, os.O_RDONLY, 0640); err != nil { return } defer file.Close() lock := &LockFile{file} pid, err = lock.ReadPid() return }
[ "func", "ReadPidFile", "(", "name", "string", ")", "(", "pid", "int", ",", "err", "error", ")", "{", "var", "file", "*", "os", ".", "File", "\n", "if", "file", ",", "err", "=", "os", ".", "OpenFile", "(", "name", ",", "os", ".", "O_RDONLY", ",", "0640", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "lock", ":=", "&", "LockFile", "{", "file", "}", "\n", "pid", ",", "err", "=", "lock", ".", "ReadPid", "(", ")", "\n", "return", "\n", "}" ]
// ReadPidFile reads process id from file with give name and returns pid. // If unable read from a file, returns error.
[ "ReadPidFile", "reads", "process", "id", "from", "file", "with", "give", "name", "and", "returns", "pid", ".", "If", "unable", "read", "from", "a", "file", "returns", "error", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L62-L72
train
sevlyar/go-daemon
lock_file.go
WritePid
func (file *LockFile) WritePid() (err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } var fileLen int if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil { return } if err = file.Truncate(int64(fileLen)); err != nil { return } err = file.Sync() return }
go
func (file *LockFile) WritePid() (err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } var fileLen int if fileLen, err = fmt.Fprint(file, os.Getpid()); err != nil { return } if err = file.Truncate(int64(fileLen)); err != nil { return } err = file.Sync() return }
[ "func", "(", "file", "*", "LockFile", ")", "WritePid", "(", ")", "(", "err", "error", ")", "{", "if", "_", ",", "err", "=", "file", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "var", "fileLen", "int", "\n", "if", "fileLen", ",", "err", "=", "fmt", ".", "Fprint", "(", "file", ",", "os", ".", "Getpid", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", "=", "file", ".", "Truncate", "(", "int64", "(", "fileLen", ")", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "err", "=", "file", ".", "Sync", "(", ")", "\n", "return", "\n", "}" ]
// WritePid writes current process id to an open file.
[ "WritePid", "writes", "current", "process", "id", "to", "an", "open", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L75-L88
train
sevlyar/go-daemon
lock_file.go
ReadPid
func (file *LockFile) ReadPid() (pid int, err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } _, err = fmt.Fscan(file, &pid) return }
go
func (file *LockFile) ReadPid() (pid int, err error) { if _, err = file.Seek(0, os.SEEK_SET); err != nil { return } _, err = fmt.Fscan(file, &pid) return }
[ "func", "(", "file", "*", "LockFile", ")", "ReadPid", "(", ")", "(", "pid", "int", ",", "err", "error", ")", "{", "if", "_", ",", "err", "=", "file", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "_", ",", "err", "=", "fmt", ".", "Fscan", "(", "file", ",", "&", "pid", ")", "\n", "return", "\n", "}" ]
// ReadPid reads process id from file and returns pid. // If unable read from a file, returns error.
[ "ReadPid", "reads", "process", "id", "from", "file", "and", "returns", "pid", ".", "If", "unable", "read", "from", "a", "file", "returns", "error", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L92-L98
train
sevlyar/go-daemon
lock_file.go
Remove
func (file *LockFile) Remove() error { defer file.Close() if err := file.Unlock(); err != nil { return err } return os.Remove(file.Name()) }
go
func (file *LockFile) Remove() error { defer file.Close() if err := file.Unlock(); err != nil { return err } return os.Remove(file.Name()) }
[ "func", "(", "file", "*", "LockFile", ")", "Remove", "(", ")", "error", "{", "defer", "file", ".", "Close", "(", ")", "\n", "if", "err", ":=", "file", ".", "Unlock", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "os", ".", "Remove", "(", "file", ".", "Name", "(", ")", ")", "\n", "}" ]
// Remove removes lock, closes and removes an open file.
[ "Remove", "removes", "lock", "closes", "and", "removes", "an", "open", "file", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/lock_file.go#L101-L109
train
sevlyar/go-daemon
command.go
AddCommand
func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) { if f != nil { AddFlag(f, sig) } if handler != nil { SetSigHandler(handler, sig) } }
go
func AddCommand(f Flag, sig os.Signal, handler SignalHandlerFunc) { if f != nil { AddFlag(f, sig) } if handler != nil { SetSigHandler(handler, sig) } }
[ "func", "AddCommand", "(", "f", "Flag", ",", "sig", "os", ".", "Signal", ",", "handler", "SignalHandlerFunc", ")", "{", "if", "f", "!=", "nil", "{", "AddFlag", "(", "f", ",", "sig", ")", "\n", "}", "\n", "if", "handler", "!=", "nil", "{", "SetSigHandler", "(", "handler", ",", "sig", ")", "\n", "}", "\n", "}" ]
// AddCommand is wrapper on AddFlag and SetSigHandler functions.
[ "AddCommand", "is", "wrapper", "on", "AddFlag", "and", "SetSigHandler", "functions", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/command.go#L8-L15
train
sevlyar/go-daemon
command.go
SendCommands
func SendCommands(p *os.Process) (err error) { for _, sig := range signals() { if err = p.Signal(sig); err != nil { return } } return }
go
func SendCommands(p *os.Process) (err error) { for _, sig := range signals() { if err = p.Signal(sig); err != nil { return } } return }
[ "func", "SendCommands", "(", "p", "*", "os", ".", "Process", ")", "(", "err", "error", ")", "{", "for", "_", ",", "sig", ":=", "range", "signals", "(", ")", "{", "if", "err", "=", "p", ".", "Signal", "(", "sig", ")", ";", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// SendCommands sends active signals to the given process.
[ "SendCommands", "sends", "active", "signals", "to", "the", "given", "process", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/command.go#L71-L78
train
sevlyar/go-daemon
command.go
ActiveFlags
func ActiveFlags() (ret []Flag) { ret = make([]Flag, 0, 1) for f := range flags { if f.IsSet() { ret = append(ret, f) } } return }
go
func ActiveFlags() (ret []Flag) { ret = make([]Flag, 0, 1) for f := range flags { if f.IsSet() { ret = append(ret, f) } } return }
[ "func", "ActiveFlags", "(", ")", "(", "ret", "[", "]", "Flag", ")", "{", "ret", "=", "make", "(", "[", "]", "Flag", ",", "0", ",", "1", ")", "\n", "for", "f", ":=", "range", "flags", "{", "if", "f", ".", "IsSet", "(", ")", "{", "ret", "=", "append", "(", "ret", ",", "f", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// ActiveFlags returns flags that has the state 'set'.
[ "ActiveFlags", "returns", "flags", "that", "has", "the", "state", "set", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/command.go#L81-L89
train
sevlyar/go-daemon
signal.go
SetSigHandler
func SetSigHandler(handler SignalHandlerFunc, signals ...os.Signal) { for _, sig := range signals { handlers[sig] = handler } }
go
func SetSigHandler(handler SignalHandlerFunc, signals ...os.Signal) { for _, sig := range signals { handlers[sig] = handler } }
[ "func", "SetSigHandler", "(", "handler", "SignalHandlerFunc", ",", "signals", "...", "os", ".", "Signal", ")", "{", "for", "_", ",", "sig", ":=", "range", "signals", "{", "handlers", "[", "sig", "]", "=", "handler", "\n", "}", "\n", "}" ]
// SetSigHandler sets handler for the given signals. // SIGTERM has the default handler, he returns ErrStop.
[ "SetSigHandler", "sets", "handler", "for", "the", "given", "signals", ".", "SIGTERM", "has", "the", "default", "handler", "he", "returns", "ErrStop", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/signal.go#L19-L23
train
sevlyar/go-daemon
signal.go
ServeSignals
func ServeSignals() (err error) { signals := make([]os.Signal, 0, len(handlers)) for sig := range handlers { signals = append(signals, sig) } ch := make(chan os.Signal, 8) signal.Notify(ch, signals...) for sig := range ch { err = handlers[sig](sig) if err != nil { break } } signal.Stop(ch) if err == ErrStop { err = nil } return }
go
func ServeSignals() (err error) { signals := make([]os.Signal, 0, len(handlers)) for sig := range handlers { signals = append(signals, sig) } ch := make(chan os.Signal, 8) signal.Notify(ch, signals...) for sig := range ch { err = handlers[sig](sig) if err != nil { break } } signal.Stop(ch) if err == ErrStop { err = nil } return }
[ "func", "ServeSignals", "(", ")", "(", "err", "error", ")", "{", "signals", ":=", "make", "(", "[", "]", "os", ".", "Signal", ",", "0", ",", "len", "(", "handlers", ")", ")", "\n", "for", "sig", ":=", "range", "handlers", "{", "signals", "=", "append", "(", "signals", ",", "sig", ")", "\n", "}", "\n", "ch", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "8", ")", "\n", "signal", ".", "Notify", "(", "ch", ",", "signals", "...", ")", "\n", "for", "sig", ":=", "range", "ch", "{", "err", "=", "handlers", "[", "sig", "]", "(", "sig", ")", "\n", "if", "err", "!=", "nil", "{", "break", "\n", "}", "\n", "}", "\n", "signal", ".", "Stop", "(", "ch", ")", "\n", "if", "err", "==", "ErrStop", "{", "err", "=", "nil", "\n", "}", "\n", "return", "\n", "}" ]
// ServeSignals calls handlers for system signals.
[ "ServeSignals", "calls", "handlers", "for", "system", "signals", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/signal.go#L26-L49
train
sevlyar/go-daemon
daemon.go
Search
func (d *Context) Search() (daemon *os.Process, err error) { return d.search() }
go
func (d *Context) Search() (daemon *os.Process, err error) { return d.search() }
[ "func", "(", "d", "*", "Context", ")", "Search", "(", ")", "(", "daemon", "*", "os", ".", "Process", ",", "err", "error", ")", "{", "return", "d", ".", "search", "(", ")", "\n", "}" ]
// Search searches daemons process by given in context pid file name. // If success returns pointer on daemons os.Process structure, // else returns error. Returns nil if filename is empty.
[ "Search", "searches", "daemons", "process", "by", "given", "in", "context", "pid", "file", "name", ".", "If", "success", "returns", "pointer", "on", "daemons", "os", ".", "Process", "structure", "else", "returns", "error", ".", "Returns", "nil", "if", "filename", "is", "empty", "." ]
fedf95d0cd0be92511436dbc84c290ff1c104f61
https://github.com/sevlyar/go-daemon/blob/fedf95d0cd0be92511436dbc84c290ff1c104f61/daemon.go#L37-L39
train
aelsabbahy/goss
resource/gomega.go
sanitizeExpectedValue
func sanitizeExpectedValue(i interface{}) interface{} { if e, ok := i.(float64); ok { return int(e) } if e, ok := i.(map[interface{}]interface{}); ok { out := make(map[string]interface{}) for k, v := range e { ks, ok := k.(string) if !ok { panic(fmt.Sprintf("Matcher key type not string: %T\n\n", k)) } out[ks] = sanitizeExpectedValue(v) } return out } return i }
go
func sanitizeExpectedValue(i interface{}) interface{} { if e, ok := i.(float64); ok { return int(e) } if e, ok := i.(map[interface{}]interface{}); ok { out := make(map[string]interface{}) for k, v := range e { ks, ok := k.(string) if !ok { panic(fmt.Sprintf("Matcher key type not string: %T\n\n", k)) } out[ks] = sanitizeExpectedValue(v) } return out } return i }
[ "func", "sanitizeExpectedValue", "(", "i", "interface", "{", "}", ")", "interface", "{", "}", "{", "if", "e", ",", "ok", ":=", "i", ".", "(", "float64", ")", ";", "ok", "{", "return", "int", "(", "e", ")", "\n", "}", "\n", "if", "e", ",", "ok", ":=", "i", ".", "(", "map", "[", "interface", "{", "}", "]", "interface", "{", "}", ")", ";", "ok", "{", "out", ":=", "make", "(", "map", "[", "string", "]", "interface", "{", "}", ")", "\n", "for", "k", ",", "v", ":=", "range", "e", "{", "ks", ",", "ok", ":=", "k", ".", "(", "string", ")", "\n", "if", "!", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Matcher key type not string: %T\\n\\n\"", ",", "\\n", ")", ")", "\n", "}", "\n", "\\n", "\n", "}", "\n", "k", "\n", "}", "\n", "out", "[", "ks", "]", "=", "sanitizeExpectedValue", "(", "v", ")", "\n", "}" ]
// Normalize expectedValue so json and yaml are the same
[ "Normalize", "expectedValue", "so", "json", "and", "yaml", "are", "the", "same" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/resource/gomega.go#L160-L176
train
aelsabbahy/goss
system/system.go
detectPackage
func (sys *System) detectPackage(c *cli.Context) { p := c.GlobalString("package") if p != "deb" && p != "apk" && p != "pacman" && p != "rpm" { p = DetectPackageManager() } switch p { case "deb": sys.NewPackage = NewDebPackage case "apk": sys.NewPackage = NewAlpinePackage case "pacman": sys.NewPackage = NewPacmanPackage default: sys.NewPackage = NewRpmPackage } }
go
func (sys *System) detectPackage(c *cli.Context) { p := c.GlobalString("package") if p != "deb" && p != "apk" && p != "pacman" && p != "rpm" { p = DetectPackageManager() } switch p { case "deb": sys.NewPackage = NewDebPackage case "apk": sys.NewPackage = NewAlpinePackage case "pacman": sys.NewPackage = NewPacmanPackage default: sys.NewPackage = NewRpmPackage } }
[ "func", "(", "sys", "*", "System", ")", "detectPackage", "(", "c", "*", "cli", ".", "Context", ")", "{", "p", ":=", "c", ".", "GlobalString", "(", "\"package\"", ")", "\n", "if", "p", "!=", "\"deb\"", "&&", "p", "!=", "\"apk\"", "&&", "p", "!=", "\"pacman\"", "&&", "p", "!=", "\"rpm\"", "{", "p", "=", "DetectPackageManager", "(", ")", "\n", "}", "\n", "switch", "p", "{", "case", "\"deb\"", ":", "sys", ".", "NewPackage", "=", "NewDebPackage", "\n", "case", "\"apk\"", ":", "sys", ".", "NewPackage", "=", "NewAlpinePackage", "\n", "case", "\"pacman\"", ":", "sys", ".", "NewPackage", "=", "NewPacmanPackage", "\n", "default", ":", "sys", ".", "NewPackage", "=", "NewRpmPackage", "\n", "}", "\n", "}" ]
// detectPackage adds the correct package creation function to a System struct
[ "detectPackage", "adds", "the", "correct", "package", "creation", "function", "to", "a", "System", "struct" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/system.go#L79-L94
train
aelsabbahy/goss
system/system.go
detectService
func (sys *System) detectService() { switch DetectService() { case "upstart": sys.NewService = NewServiceUpstart case "systemd": sys.NewService = NewServiceSystemd case "alpineinit": sys.NewService = NewAlpineServiceInit default: sys.NewService = NewServiceInit } }
go
func (sys *System) detectService() { switch DetectService() { case "upstart": sys.NewService = NewServiceUpstart case "systemd": sys.NewService = NewServiceSystemd case "alpineinit": sys.NewService = NewAlpineServiceInit default: sys.NewService = NewServiceInit } }
[ "func", "(", "sys", "*", "System", ")", "detectService", "(", ")", "{", "switch", "DetectService", "(", ")", "{", "case", "\"upstart\"", ":", "sys", ".", "NewService", "=", "NewServiceUpstart", "\n", "case", "\"systemd\"", ":", "sys", ".", "NewService", "=", "NewServiceSystemd", "\n", "case", "\"alpineinit\"", ":", "sys", ".", "NewService", "=", "NewAlpineServiceInit", "\n", "default", ":", "sys", ".", "NewService", "=", "NewServiceInit", "\n", "}", "\n", "}" ]
// detectService adds the correct service creation function to a System struct
[ "detectService", "adds", "the", "correct", "service", "creation", "function", "to", "a", "System", "struct" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/system.go#L97-L108
train
aelsabbahy/goss
system/system.go
HasCommand
func HasCommand(cmd string) bool { if _, err := exec.LookPath(cmd); err == nil { return true } return false }
go
func HasCommand(cmd string) bool { if _, err := exec.LookPath(cmd); err == nil { return true } return false }
[ "func", "HasCommand", "(", "cmd", "string", ")", "bool", "{", "if", "_", ",", "err", ":=", "exec", ".", "LookPath", "(", "cmd", ")", ";", "err", "==", "nil", "{", "return", "true", "\n", "}", "\n", "return", "false", "\n", "}" ]
// HasCommand returns whether or not an executable by this name is on the PATH.
[ "HasCommand", "returns", "whether", "or", "not", "an", "executable", "by", "this", "name", "is", "on", "the", "PATH", "." ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/system.go#L174-L179
train
aelsabbahy/goss
store.go
ReadJSON
func ReadJSON(filePath string) GossConfig { file, err := ioutil.ReadFile(filePath) if err != nil { fmt.Printf("File error: %v\n", err) os.Exit(1) } return ReadJSONData(file, false) }
go
func ReadJSON(filePath string) GossConfig { file, err := ioutil.ReadFile(filePath) if err != nil { fmt.Printf("File error: %v\n", err) os.Exit(1) } return ReadJSONData(file, false) }
[ "func", "ReadJSON", "(", "filePath", "string", ")", "GossConfig", "{", "file", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filePath", ")", "\n", "if", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"File error: %v\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Reads json file returning GossConfig
[ "Reads", "json", "file", "returning", "GossConfig" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/store.go#L56-L64
train
aelsabbahy/goss
store.go
ReadJSONData
func ReadJSONData(data []byte, detectFormat bool) GossConfig { if TemplateFilter != nil { data = TemplateFilter(data) if debug { fmt.Println("DEBUG: file after text/template render") fmt.Println(string(data)) } } format := OutStoreFormat if detectFormat == true { format = getStoreFormatFromData(data) } gossConfig := NewGossConfig() // Horrible, but will do for now if err := unmarshal(data, gossConfig, format); err != nil { // FIXME: really dude.. this is so ugly fmt.Printf("Error: %v\n", err) os.Exit(1) } return *gossConfig }
go
func ReadJSONData(data []byte, detectFormat bool) GossConfig { if TemplateFilter != nil { data = TemplateFilter(data) if debug { fmt.Println("DEBUG: file after text/template render") fmt.Println(string(data)) } } format := OutStoreFormat if detectFormat == true { format = getStoreFormatFromData(data) } gossConfig := NewGossConfig() // Horrible, but will do for now if err := unmarshal(data, gossConfig, format); err != nil { // FIXME: really dude.. this is so ugly fmt.Printf("Error: %v\n", err) os.Exit(1) } return *gossConfig }
[ "func", "ReadJSONData", "(", "data", "[", "]", "byte", ",", "detectFormat", "bool", ")", "GossConfig", "{", "if", "TemplateFilter", "!=", "nil", "{", "data", "=", "TemplateFilter", "(", "data", ")", "\n", "if", "debug", "{", "fmt", ".", "Println", "(", "\"DEBUG: file after text/template render\"", ")", "\n", "fmt", ".", "Println", "(", "string", "(", "data", ")", ")", "\n", "}", "\n", "}", "\n", "format", ":=", "OutStoreFormat", "\n", "if", "detectFormat", "==", "true", "{", "format", "=", "getStoreFormatFromData", "(", "data", ")", "\n", "}", "\n", "gossConfig", ":=", "NewGossConfig", "(", ")", "\n", "if", "err", ":=", "unmarshal", "(", "data", ",", "gossConfig", ",", "format", ")", ";", "err", "!=", "nil", "{", "fmt", ".", "Printf", "(", "\"Error: %v\\n\"", ",", "\\n", ")", "\n", "err", "\n", "}", "\n", "os", ".", "Exit", "(", "1", ")", "\n", "}" ]
// Reads json byte array returning GossConfig
[ "Reads", "json", "byte", "array", "returning", "GossConfig" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/store.go#L96-L116
train
aelsabbahy/goss
store.go
RenderJSON
func RenderJSON(c *cli.Context) string { filePath := c.GlobalString("gossfile") varsFile := c.GlobalString("vars") debug = c.Bool("debug") TemplateFilter = NewTemplateFilter(varsFile) path := filepath.Dir(filePath) OutStoreFormat = getStoreFormatFromFileName(filePath) gossConfig := mergeJSONData(ReadJSON(filePath), 0, path) b, err := marshal(gossConfig) if err != nil { log.Fatalf("Error rendering: %v\n", err) } return string(b) }
go
func RenderJSON(c *cli.Context) string { filePath := c.GlobalString("gossfile") varsFile := c.GlobalString("vars") debug = c.Bool("debug") TemplateFilter = NewTemplateFilter(varsFile) path := filepath.Dir(filePath) OutStoreFormat = getStoreFormatFromFileName(filePath) gossConfig := mergeJSONData(ReadJSON(filePath), 0, path) b, err := marshal(gossConfig) if err != nil { log.Fatalf("Error rendering: %v\n", err) } return string(b) }
[ "func", "RenderJSON", "(", "c", "*", "cli", ".", "Context", ")", "string", "{", "filePath", ":=", "c", ".", "GlobalString", "(", "\"gossfile\"", ")", "\n", "varsFile", ":=", "c", ".", "GlobalString", "(", "\"vars\"", ")", "\n", "debug", "=", "c", ".", "Bool", "(", "\"debug\"", ")", "\n", "TemplateFilter", "=", "NewTemplateFilter", "(", "varsFile", ")", "\n", "path", ":=", "filepath", ".", "Dir", "(", "filePath", ")", "\n", "OutStoreFormat", "=", "getStoreFormatFromFileName", "(", "filePath", ")", "\n", "gossConfig", ":=", "mergeJSONData", "(", "ReadJSON", "(", "filePath", ")", ",", "0", ",", "path", ")", "\n", "b", ",", "err", ":=", "marshal", "(", "gossConfig", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Fatalf", "(", "\"Error rendering: %v\\n\"", ",", "\\n", ")", "\n", "}", "\n", "err", "\n", "}" ]
// Reads json file recursively returning string
[ "Reads", "json", "file", "recursively", "returning", "string" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/store.go#L119-L133
train
aelsabbahy/goss
outputs/outputs.go
Outputers
func Outputers() []string { outputersMu.Lock() defer outputersMu.Unlock() var list []string for name := range outputers { list = append(list, name) } sort.Strings(list) return list }
go
func Outputers() []string { outputersMu.Lock() defer outputersMu.Unlock() var list []string for name := range outputers { list = append(list, name) } sort.Strings(list) return list }
[ "func", "Outputers", "(", ")", "[", "]", "string", "{", "outputersMu", ".", "Lock", "(", ")", "\n", "defer", "outputersMu", ".", "Unlock", "(", ")", "\n", "var", "list", "[", "]", "string", "\n", "for", "name", ":=", "range", "outputers", "{", "list", "=", "append", "(", "list", ",", "name", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "list", ")", "\n", "return", "list", "\n", "}" ]
// Outputers returns a sorted list of the names of the registered outputers.
[ "Outputers", "returns", "a", "sorted", "list", "of", "the", "names", "of", "the", "registered", "outputers", "." ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/outputs/outputs.go#L102-L111
train
aelsabbahy/goss
system/dns.go
LookupHost
func LookupHost(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { a, _ := LookupA(host, server, c, m) aaaa, _ := LookupAAAA(host, server, c, m) addrs = append(a, aaaa...) return }
go
func LookupHost(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { a, _ := LookupA(host, server, c, m) aaaa, _ := LookupAAAA(host, server, c, m) addrs = append(a, aaaa...) return }
[ "func", "LookupHost", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "a", ",", "_", ":=", "LookupA", "(", "host", ",", "server", ",", "c", ",", "m", ")", "\n", "aaaa", ",", "_", ":=", "LookupAAAA", "(", "host", ",", "server", ",", "c", ",", "m", ")", "\n", "addrs", "=", "append", "(", "a", ",", "aaaa", "...", ")", "\n", "return", "\n", "}" ]
// A and AAAA record lookup - similar to net.LookupHost
[ "A", "and", "AAAA", "record", "lookup", "-", "similar", "to", "net", ".", "LookupHost" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L162-L168
train
aelsabbahy/goss
system/dns.go
LookupCNAME
func LookupCNAME(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeCNAME) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.CNAME); ok { addrs = append(addrs, t.Target) } } return }
go
func LookupCNAME(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeCNAME) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.CNAME); ok { addrs = append(addrs, t.Target) } } return }
[ "func", "LookupCNAME", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeCNAME", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "CNAME", ")", ";", "ok", "{", "addrs", "=", "append", "(", "addrs", ",", "t", ".", "Target", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// CNAME record lookup
[ "CNAME", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L205-L219
train
aelsabbahy/goss
system/dns.go
LookupMX
func LookupMX(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeMX) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.MX); ok { mxstring := strconv.Itoa(int(t.Preference)) + " " + t.Mx addrs = append(addrs, mxstring) } } return }
go
func LookupMX(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeMX) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.MX); ok { mxstring := strconv.Itoa(int(t.Preference)) + " " + t.Mx addrs = append(addrs, mxstring) } } return }
[ "func", "LookupMX", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeMX", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "MX", ")", ";", "ok", "{", "mxstring", ":=", "strconv", ".", "Itoa", "(", "int", "(", "t", ".", "Preference", ")", ")", "+", "\" \"", "+", "t", ".", "Mx", "\n", "addrs", "=", "append", "(", "addrs", ",", "mxstring", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// MX record lookup
[ "MX", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L222-L237
train
aelsabbahy/goss
system/dns.go
LookupNS
func LookupNS(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeNS) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.NS); ok { addrs = append(addrs, t.Ns) } } return }
go
func LookupNS(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeNS) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.NS); ok { addrs = append(addrs, t.Ns) } } return }
[ "func", "LookupNS", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeNS", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "NS", ")", ";", "ok", "{", "addrs", "=", "append", "(", "addrs", ",", "t", ".", "Ns", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// NS record lookup
[ "NS", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L240-L254
train
aelsabbahy/goss
system/dns.go
LookupSRV
func LookupSRV(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeSRV) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.SRV); ok { prio := strconv.Itoa(int(t.Priority)) weight := strconv.Itoa(int(t.Weight)) port := strconv.Itoa(int(t.Port)) srvrec := strings.Join([]string{prio, weight, port, t.Target}, " ") addrs = append(addrs, srvrec) } } return }
go
func LookupSRV(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeSRV) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.SRV); ok { prio := strconv.Itoa(int(t.Priority)) weight := strconv.Itoa(int(t.Weight)) port := strconv.Itoa(int(t.Port)) srvrec := strings.Join([]string{prio, weight, port, t.Target}, " ") addrs = append(addrs, srvrec) } } return }
[ "func", "LookupSRV", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeSRV", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "SRV", ")", ";", "ok", "{", "prio", ":=", "strconv", ".", "Itoa", "(", "int", "(", "t", ".", "Priority", ")", ")", "\n", "weight", ":=", "strconv", ".", "Itoa", "(", "int", "(", "t", ".", "Weight", ")", ")", "\n", "port", ":=", "strconv", ".", "Itoa", "(", "int", "(", "t", ".", "Port", ")", ")", "\n", "srvrec", ":=", "strings", ".", "Join", "(", "[", "]", "string", "{", "prio", ",", "weight", ",", "port", ",", "t", ".", "Target", "}", ",", "\" \"", ")", "\n", "addrs", "=", "append", "(", "addrs", ",", "srvrec", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// SRV record lookup
[ "SRV", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L257-L275
train
aelsabbahy/goss
system/dns.go
LookupTXT
func LookupTXT(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeTXT) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.TXT); ok { addrs = append(addrs, t.Txt...) } } return }
go
func LookupTXT(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeTXT) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.TXT); ok { addrs = append(addrs, t.Txt...) } } return }
[ "func", "LookupTXT", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeTXT", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "TXT", ")", ";", "ok", "{", "addrs", "=", "append", "(", "addrs", ",", "t", ".", "Txt", "...", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// TXT record lookup
[ "TXT", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L278-L292
train
aelsabbahy/goss
system/dns.go
LookupPTR
func LookupPTR(addr string, server string, c *dns.Client, m *dns.Msg) (name []string, err error) { reverse, err := dns.ReverseAddr(addr) if err != nil { return nil, err } m.SetQuestion(reverse, dns.TypePTR) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { name = append(name, ans.(*dns.PTR).Ptr) } return }
go
func LookupPTR(addr string, server string, c *dns.Client, m *dns.Msg) (name []string, err error) { reverse, err := dns.ReverseAddr(addr) if err != nil { return nil, err } m.SetQuestion(reverse, dns.TypePTR) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { name = append(name, ans.(*dns.PTR).Ptr) } return }
[ "func", "LookupPTR", "(", "addr", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "name", "[", "]", "string", ",", "err", "error", ")", "{", "reverse", ",", "err", ":=", "dns", ".", "ReverseAddr", "(", "addr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "m", ".", "SetQuestion", "(", "reverse", ",", "dns", ".", "TypePTR", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "name", "=", "append", "(", "name", ",", "ans", ".", "(", "*", "dns", ".", "PTR", ")", ".", "Ptr", ")", "\n", "}", "\n", "return", "\n", "}" ]
// PTR record lookup
[ "PTR", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L295-L314
train
aelsabbahy/goss
system/dns.go
LookupCAA
func LookupCAA(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeCAA) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.CAA); ok { flag := strconv.Itoa(int(t.Flag)) caarec := strings.Join([]string{flag, t.Tag, t.Value}, " ") addrs = append(addrs, caarec) } } return }
go
func LookupCAA(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) { m.SetQuestion(dns.Fqdn(host), dns.TypeCAA) r, _, err := c.Exchange(m, net.JoinHostPort(server, "53")) if err != nil { return nil, err } for _, ans := range r.Answer { if t, ok := ans.(*dns.CAA); ok { flag := strconv.Itoa(int(t.Flag)) caarec := strings.Join([]string{flag, t.Tag, t.Value}, " ") addrs = append(addrs, caarec) } } return }
[ "func", "LookupCAA", "(", "host", "string", ",", "server", "string", ",", "c", "*", "dns", ".", "Client", ",", "m", "*", "dns", ".", "Msg", ")", "(", "addrs", "[", "]", "string", ",", "err", "error", ")", "{", "m", ".", "SetQuestion", "(", "dns", ".", "Fqdn", "(", "host", ")", ",", "dns", ".", "TypeCAA", ")", "\n", "r", ",", "_", ",", "err", ":=", "c", ".", "Exchange", "(", "m", ",", "net", ".", "JoinHostPort", "(", "server", ",", "\"53\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ans", ":=", "range", "r", ".", "Answer", "{", "if", "t", ",", "ok", ":=", "ans", ".", "(", "*", "dns", ".", "CAA", ")", ";", "ok", "{", "flag", ":=", "strconv", ".", "Itoa", "(", "int", "(", "t", ".", "Flag", ")", ")", "\n", "caarec", ":=", "strings", ".", "Join", "(", "[", "]", "string", "{", "flag", ",", "t", ".", "Tag", ",", "t", ".", "Value", "}", ",", "\" \"", ")", "\n", "addrs", "=", "append", "(", "addrs", ",", "caarec", ")", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// CAA record lookup
[ "CAA", "record", "lookup" ]
9c0d41fbdc8280be6a917e951acaf48f1f5c1f07
https://github.com/aelsabbahy/goss/blob/9c0d41fbdc8280be6a917e951acaf48f1f5c1f07/system/dns.go#L317-L333
train
ahmdrz/goinsta
timeline.go
Stories
func (time *Timeline) Stories() (*Tray, error) { body, err := time.inst.sendSimpleRequest(urlStories) if err == nil { tray := &Tray{} err = json.Unmarshal(body, tray) if err != nil { return nil, err } tray.set(time.inst, urlStories) return tray, nil } return nil, err }
go
func (time *Timeline) Stories() (*Tray, error) { body, err := time.inst.sendSimpleRequest(urlStories) if err == nil { tray := &Tray{} err = json.Unmarshal(body, tray) if err != nil { return nil, err } tray.set(time.inst, urlStories) return tray, nil } return nil, err }
[ "func", "(", "time", "*", "Timeline", ")", "Stories", "(", ")", "(", "*", "Tray", ",", "error", ")", "{", "body", ",", "err", ":=", "time", ".", "inst", ".", "sendSimpleRequest", "(", "urlStories", ")", "\n", "if", "err", "==", "nil", "{", "tray", ":=", "&", "Tray", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "tray", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "tray", ".", "set", "(", "time", ".", "inst", ",", "urlStories", ")", "\n", "return", "tray", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// Stories returns slice of StoryMedia
[ "Stories", "returns", "slice", "of", "StoryMedia" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/timeline.go#L31-L43
train
ahmdrz/goinsta
goinsta.go
New
func New(username, password string) *Instagram { // this call never returns error jar, _ := cookiejar.New(nil) inst := &Instagram{ user: username, pass: password, dID: generateDeviceID( generateMD5Hash(username + password), ), uuid: generateUUID(), // both uuid must be differents pid: generateUUID(), c: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, Jar: jar, }, } inst.init() return inst }
go
func New(username, password string) *Instagram { // this call never returns error jar, _ := cookiejar.New(nil) inst := &Instagram{ user: username, pass: password, dID: generateDeviceID( generateMD5Hash(username + password), ), uuid: generateUUID(), // both uuid must be differents pid: generateUUID(), c: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, Jar: jar, }, } inst.init() return inst }
[ "func", "New", "(", "username", ",", "password", "string", ")", "*", "Instagram", "{", "jar", ",", "_", ":=", "cookiejar", ".", "New", "(", "nil", ")", "\n", "inst", ":=", "&", "Instagram", "{", "user", ":", "username", ",", "pass", ":", "password", ",", "dID", ":", "generateDeviceID", "(", "generateMD5Hash", "(", "username", "+", "password", ")", ",", ")", ",", "uuid", ":", "generateUUID", "(", ")", ",", "pid", ":", "generateUUID", "(", ")", ",", "c", ":", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "}", ",", "Jar", ":", "jar", ",", "}", ",", "}", "\n", "inst", ".", "init", "(", ")", "\n", "return", "inst", "\n", "}" ]
// New creates Instagram structure
[ "New", "creates", "Instagram", "structure" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L96-L117
train
ahmdrz/goinsta
goinsta.go
SetProxy
func (inst *Instagram) SetProxy(url string, insecure bool) error { uri, err := neturl.Parse(url) if err == nil { inst.c.Transport = &http.Transport{ Proxy: http.ProxyURL(uri), TLSClientConfig: &tls.Config{ InsecureSkipVerify: insecure, }, } } return err }
go
func (inst *Instagram) SetProxy(url string, insecure bool) error { uri, err := neturl.Parse(url) if err == nil { inst.c.Transport = &http.Transport{ Proxy: http.ProxyURL(uri), TLSClientConfig: &tls.Config{ InsecureSkipVerify: insecure, }, } } return err }
[ "func", "(", "inst", "*", "Instagram", ")", "SetProxy", "(", "url", "string", ",", "insecure", "bool", ")", "error", "{", "uri", ",", "err", ":=", "neturl", ".", "Parse", "(", "url", ")", "\n", "if", "err", "==", "nil", "{", "inst", ".", "c", ".", "Transport", "=", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyURL", "(", "uri", ")", ",", "TLSClientConfig", ":", "&", "tls", ".", "Config", "{", "InsecureSkipVerify", ":", "insecure", ",", "}", ",", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SetProxy sets proxy for connection.
[ "SetProxy", "sets", "proxy", "for", "connection", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L131-L142
train
ahmdrz/goinsta
goinsta.go
ImportReader
func ImportReader(r io.Reader) (*Instagram, error) { url, err := neturl.Parse(goInstaAPIUrl) if err != nil { return nil, err } bytes, err := ioutil.ReadAll(r) if err != nil { return nil, err } config := ConfigFile{} err = json.Unmarshal(bytes, &config) if err != nil { return nil, err } inst := &Instagram{ user: config.User, dID: config.DeviceID, uuid: config.UUID, rankToken: config.RankToken, token: config.Token, pid: config.PhoneID, c: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, }, } inst.c.Jar, err = cookiejar.New(nil) if err != nil { return inst, err } inst.c.Jar.SetCookies(url, config.Cookies) inst.init() inst.Account = &Account{inst: inst, ID: config.ID} inst.Account.Sync() return inst, nil }
go
func ImportReader(r io.Reader) (*Instagram, error) { url, err := neturl.Parse(goInstaAPIUrl) if err != nil { return nil, err } bytes, err := ioutil.ReadAll(r) if err != nil { return nil, err } config := ConfigFile{} err = json.Unmarshal(bytes, &config) if err != nil { return nil, err } inst := &Instagram{ user: config.User, dID: config.DeviceID, uuid: config.UUID, rankToken: config.RankToken, token: config.Token, pid: config.PhoneID, c: &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyFromEnvironment, }, }, } inst.c.Jar, err = cookiejar.New(nil) if err != nil { return inst, err } inst.c.Jar.SetCookies(url, config.Cookies) inst.init() inst.Account = &Account{inst: inst, ID: config.ID} inst.Account.Sync() return inst, nil }
[ "func", "ImportReader", "(", "r", "io", ".", "Reader", ")", "(", "*", "Instagram", ",", "error", ")", "{", "url", ",", "err", ":=", "neturl", ".", "Parse", "(", "goInstaAPIUrl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "bytes", ",", "err", ":=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "config", ":=", "ConfigFile", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "bytes", ",", "&", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "inst", ":=", "&", "Instagram", "{", "user", ":", "config", ".", "User", ",", "dID", ":", "config", ".", "DeviceID", ",", "uuid", ":", "config", ".", "UUID", ",", "rankToken", ":", "config", ".", "RankToken", ",", "token", ":", "config", ".", "Token", ",", "pid", ":", "config", ".", "PhoneID", ",", "c", ":", "&", "http", ".", "Client", "{", "Transport", ":", "&", "http", ".", "Transport", "{", "Proxy", ":", "http", ".", "ProxyFromEnvironment", ",", "}", ",", "}", ",", "}", "\n", "inst", ".", "c", ".", "Jar", ",", "err", "=", "cookiejar", ".", "New", "(", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "inst", ",", "err", "\n", "}", "\n", "inst", ".", "c", ".", "Jar", ".", "SetCookies", "(", "url", ",", "config", ".", "Cookies", ")", "\n", "inst", ".", "init", "(", ")", "\n", "inst", ".", "Account", "=", "&", "Account", "{", "inst", ":", "inst", ",", "ID", ":", "config", ".", "ID", "}", "\n", "inst", ".", "Account", ".", "Sync", "(", ")", "\n", "return", "inst", ",", "nil", "\n", "}" ]
// ImportReader imports instagram configuration from io.Reader // // This function does not set proxy automatically. Use SetProxy after this call.
[ "ImportReader", "imports", "instagram", "configuration", "from", "io", ".", "Reader", "This", "function", "does", "not", "set", "proxy", "automatically", ".", "Use", "SetProxy", "after", "this", "call", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L211-L251
train
ahmdrz/goinsta
goinsta.go
Import
func Import(path string) (*Instagram, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return ImportReader(f) }
go
func Import(path string) (*Instagram, error) { f, err := os.Open(path) if err != nil { return nil, err } defer f.Close() return ImportReader(f) }
[ "func", "Import", "(", "path", "string", ")", "(", "*", "Instagram", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "return", "ImportReader", "(", "f", ")", "\n", "}" ]
// Import imports instagram configuration // // This function does not set proxy automatically. Use SetProxy after this call.
[ "Import", "imports", "instagram", "configuration", "This", "function", "does", "not", "set", "proxy", "automatically", ".", "Use", "SetProxy", "after", "this", "call", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L256-L263
train
ahmdrz/goinsta
goinsta.go
Login
func (inst *Instagram) Login() error { err := inst.readMsisdnHeader() if err != nil { return err } err = inst.syncFeatures() if err != nil { return err } err = inst.zrToken() if err != nil { return err } err = inst.sendAdID() if err != nil { return err } err = inst.contactPrefill() if err != nil { return err } result, err := json.Marshal( map[string]interface{}{ "guid": inst.uuid, "login_attempt_count": 0, "_csrftoken": inst.token, "device_id": inst.dID, "adid": inst.adid, "phone_id": inst.pid, "username": inst.user, "password": inst.pass, "google_tokens": "[]", }, ) if err != nil { return err } body, err := inst.sendRequest( &reqOptions{ Endpoint: urlLogin, Query: generateSignature(b2s(result)), IsPost: true, Login: true, }, ) if err != nil { return err } inst.pass = "" // getting account data res := accountResp{} err = json.Unmarshal(body, &res) if err != nil { return err } inst.Account = &res.Account inst.Account.inst = inst inst.rankToken = strconv.FormatInt(inst.Account.ID, 10) + "_" + inst.uuid inst.zrToken() return err }
go
func (inst *Instagram) Login() error { err := inst.readMsisdnHeader() if err != nil { return err } err = inst.syncFeatures() if err != nil { return err } err = inst.zrToken() if err != nil { return err } err = inst.sendAdID() if err != nil { return err } err = inst.contactPrefill() if err != nil { return err } result, err := json.Marshal( map[string]interface{}{ "guid": inst.uuid, "login_attempt_count": 0, "_csrftoken": inst.token, "device_id": inst.dID, "adid": inst.adid, "phone_id": inst.pid, "username": inst.user, "password": inst.pass, "google_tokens": "[]", }, ) if err != nil { return err } body, err := inst.sendRequest( &reqOptions{ Endpoint: urlLogin, Query: generateSignature(b2s(result)), IsPost: true, Login: true, }, ) if err != nil { return err } inst.pass = "" // getting account data res := accountResp{} err = json.Unmarshal(body, &res) if err != nil { return err } inst.Account = &res.Account inst.Account.inst = inst inst.rankToken = strconv.FormatInt(inst.Account.ID, 10) + "_" + inst.uuid inst.zrToken() return err }
[ "func", "(", "inst", "*", "Instagram", ")", "Login", "(", ")", "error", "{", "err", ":=", "inst", ".", "readMsisdnHeader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "inst", ".", "syncFeatures", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "inst", ".", "zrToken", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "inst", ".", "sendAdID", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "inst", ".", "contactPrefill", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "result", ",", "err", ":=", "json", ".", "Marshal", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"guid\"", ":", "inst", ".", "uuid", ",", "\"login_attempt_count\"", ":", "0", ",", "\"_csrftoken\"", ":", "inst", ".", "token", ",", "\"device_id\"", ":", "inst", ".", "dID", ",", "\"adid\"", ":", "inst", ".", "adid", ",", "\"phone_id\"", ":", "inst", ".", "pid", ",", "\"username\"", ":", "inst", ".", "user", ",", "\"password\"", ":", "inst", ".", "pass", ",", "\"google_tokens\"", ":", "\"[]\"", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "inst", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlLogin", ",", "Query", ":", "generateSignature", "(", "b2s", "(", "result", ")", ")", ",", "IsPost", ":", "true", ",", "Login", ":", "true", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "inst", ".", "pass", "=", "\"\"", "\n", "res", ":=", "accountResp", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "inst", ".", "Account", "=", "&", "res", ".", "Account", "\n", "inst", ".", "Account", ".", "inst", "=", "inst", "\n", "inst", ".", "rankToken", "=", "strconv", ".", "FormatInt", "(", "inst", ".", "Account", ".", "ID", ",", "10", ")", "+", "\"_\"", "+", "inst", ".", "uuid", "\n", "inst", ".", "zrToken", "(", ")", "\n", "return", "err", "\n", "}" ]
// Login performs instagram login. // // Password will be deleted after login
[ "Login", "performs", "instagram", "login", ".", "Password", "will", "be", "deleted", "after", "login" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L347-L415
train
ahmdrz/goinsta
goinsta.go
Logout
func (inst *Instagram) Logout() error { _, err := inst.sendSimpleRequest(urlLogout) inst.c.Jar = nil inst.c = nil return err }
go
func (inst *Instagram) Logout() error { _, err := inst.sendSimpleRequest(urlLogout) inst.c.Jar = nil inst.c = nil return err }
[ "func", "(", "inst", "*", "Instagram", ")", "Logout", "(", ")", "error", "{", "_", ",", "err", ":=", "inst", ".", "sendSimpleRequest", "(", "urlLogout", ")", "\n", "inst", ".", "c", ".", "Jar", "=", "nil", "\n", "inst", ".", "c", "=", "nil", "\n", "return", "err", "\n", "}" ]
// Logout closes current session
[ "Logout", "closes", "current", "session" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/goinsta.go#L418-L423
train
ahmdrz/goinsta
search.go
User
func (search *Search) User(user string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchUser, Query: map[string]string{ "ig_sig_key_version": goInstaSigKeyVersion, "is_typeahead": "true", "query": user, "rank_token": insta.rankToken, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
go
func (search *Search) User(user string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchUser, Query: map[string]string{ "ig_sig_key_version": goInstaSigKeyVersion, "is_typeahead": "true", "query": user, "rank_token": insta.rankToken, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
[ "func", "(", "search", "*", "Search", ")", "User", "(", "user", "string", ")", "(", "*", "SearchResult", ",", "error", ")", "{", "insta", ":=", "search", ".", "inst", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlSearchUser", ",", "Query", ":", "map", "[", "string", "]", "string", "{", "\"ig_sig_key_version\"", ":", "goInstaSigKeyVersion", ",", "\"is_typeahead\"", ":", "\"true\"", ",", "\"query\"", ":", "user", ",", "\"rank_token\"", ":", "insta", ".", "rankToken", ",", "}", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "res", ":=", "&", "SearchResult", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "res", ")", "\n", "return", "res", ",", "err", "\n", "}" ]
// User search by username
[ "User", "search", "by", "username" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/search.go#L73-L93
train
ahmdrz/goinsta
search.go
Tags
func (search *Search) Tags(tag string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchTag, Query: map[string]string{ "is_typeahead": "true", "rank_token": insta.rankToken, "q": tag, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
go
func (search *Search) Tags(tag string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchTag, Query: map[string]string{ "is_typeahead": "true", "rank_token": insta.rankToken, "q": tag, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
[ "func", "(", "search", "*", "Search", ")", "Tags", "(", "tag", "string", ")", "(", "*", "SearchResult", ",", "error", ")", "{", "insta", ":=", "search", ".", "inst", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlSearchTag", ",", "Query", ":", "map", "[", "string", "]", "string", "{", "\"is_typeahead\"", ":", "\"true\"", ",", "\"rank_token\"", ":", "insta", ".", "rankToken", ",", "\"q\"", ":", "tag", ",", "}", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "res", ":=", "&", "SearchResult", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "res", ")", "\n", "return", "res", ",", "err", "\n", "}" ]
// Tags search by tag
[ "Tags", "search", "by", "tag" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/search.go#L96-L115
train
ahmdrz/goinsta
search.go
Facebook
func (search *Search) Facebook(user string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchFacebook, Query: map[string]string{ "query": user, "rank_token": insta.rankToken, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
go
func (search *Search) Facebook(user string) (*SearchResult, error) { insta := search.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSearchFacebook, Query: map[string]string{ "query": user, "rank_token": insta.rankToken, }, }, ) if err != nil { return nil, err } res := &SearchResult{} err = json.Unmarshal(body, res) return res, err }
[ "func", "(", "search", "*", "Search", ")", "Facebook", "(", "user", "string", ")", "(", "*", "SearchResult", ",", "error", ")", "{", "insta", ":=", "search", ".", "inst", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlSearchFacebook", ",", "Query", ":", "map", "[", "string", "]", "string", "{", "\"query\"", ":", "user", ",", "\"rank_token\"", ":", "insta", ".", "rankToken", ",", "}", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "res", ":=", "&", "SearchResult", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "res", ")", "\n", "return", "res", ",", "err", "\n", "}" ]
// Facebook search by facebook user.
[ "Facebook", "search", "by", "facebook", "user", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/search.go#L151-L168
train
ahmdrz/goinsta
types.go
GetBest
func (img Images) GetBest() string { best := "" var mh, mw int for _, v := range img.Versions { if v.Width > mw || v.Height > mh { best = v.URL mh, mw = v.Height, v.Width } } return best }
go
func (img Images) GetBest() string { best := "" var mh, mw int for _, v := range img.Versions { if v.Width > mw || v.Height > mh { best = v.URL mh, mw = v.Height, v.Width } } return best }
[ "func", "(", "img", "Images", ")", "GetBest", "(", ")", "string", "{", "best", ":=", "\"\"", "\n", "var", "mh", ",", "mw", "int", "\n", "for", "_", ",", "v", ":=", "range", "img", ".", "Versions", "{", "if", "v", ".", "Width", ">", "mw", "||", "v", ".", "Height", ">", "mh", "{", "best", "=", "v", ".", "URL", "\n", "mh", ",", "mw", "=", "v", ".", "Height", ",", "v", ".", "Width", "\n", "}", "\n", "}", "\n", "return", "best", "\n", "}" ]
// GetBest returns the URL of the image with the best quality.
[ "GetBest", "returns", "the", "URL", "of", "the", "image", "with", "the", "best", "quality", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/types.go#L149-L159
train
ahmdrz/goinsta
types.go
Unblock
func (b *BlockedUser) Unblock() error { u := User{ID: b.UserID} return u.Unblock() }
go
func (b *BlockedUser) Unblock() error { u := User{ID: b.UserID} return u.Unblock() }
[ "func", "(", "b", "*", "BlockedUser", ")", "Unblock", "(", ")", "error", "{", "u", ":=", "User", "{", "ID", ":", "b", ".", "UserID", "}", "\n", "return", "u", ".", "Unblock", "(", ")", "\n", "}" ]
// Unblock unblocks blocked user.
[ "Unblock", "unblocks", "blocked", "user", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/types.go#L297-L300
train
ahmdrz/goinsta
utils.go
getImageDimensionFromReader
func getImageDimensionFromReader(rdr io.Reader) (int, int, error) { image, _, err := image.DecodeConfig(rdr) if err != nil { return 0, 0, err } return image.Width, image.Height, nil }
go
func getImageDimensionFromReader(rdr io.Reader) (int, int, error) { image, _, err := image.DecodeConfig(rdr) if err != nil { return 0, 0, err } return image.Width, image.Height, nil }
[ "func", "getImageDimensionFromReader", "(", "rdr", "io", ".", "Reader", ")", "(", "int", ",", "int", ",", "error", ")", "{", "image", ",", "_", ",", "err", ":=", "image", ".", "DecodeConfig", "(", "rdr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "0", ",", "err", "\n", "}", "\n", "return", "image", ".", "Width", ",", "image", ".", "Height", ",", "nil", "\n", "}" ]
// getImageDimensionFromReader return image dimension , types is .jpg and .png
[ "getImageDimensionFromReader", "return", "image", "dimension", "types", "is", ".", "jpg", "and", ".", "png" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/utils.go#L75-L81
train
ahmdrz/goinsta
account.go
Sync
func (account *Account) Sync() error { insta := account.inst data, err := insta.prepareData() if err != nil { return err } body, err := insta.sendRequest(&reqOptions{ Endpoint: urlCurrentUser, Query: generateSignature(data), IsPost: true, }) if err == nil { resp := profResp{} err = json.Unmarshal(body, &resp) if err == nil { *account = resp.Account account.inst = insta } } return err }
go
func (account *Account) Sync() error { insta := account.inst data, err := insta.prepareData() if err != nil { return err } body, err := insta.sendRequest(&reqOptions{ Endpoint: urlCurrentUser, Query: generateSignature(data), IsPost: true, }) if err == nil { resp := profResp{} err = json.Unmarshal(body, &resp) if err == nil { *account = resp.Account account.inst = insta } } return err }
[ "func", "(", "account", "*", "Account", ")", "Sync", "(", ")", "error", "{", "insta", ":=", "account", ".", "inst", "\n", "data", ",", "err", ":=", "insta", ".", "prepareData", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlCurrentUser", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "true", ",", "}", ")", "\n", "if", "err", "==", "nil", "{", "resp", ":=", "profResp", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "if", "err", "==", "nil", "{", "*", "account", "=", "resp", ".", "Account", "\n", "account", ".", "inst", "=", "insta", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Sync updates account information
[ "Sync", "updates", "account", "information" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/account.go#L74-L94
train
ahmdrz/goinsta
account.go
Saved
func (account *Account) Saved() (*SavedMedia, error) { body, err := account.inst.sendSimpleRequest(urlUserTags, account.ID) if err == nil { media := &SavedMedia{} err = json.Unmarshal(body, &media) return media, err } return nil, err }
go
func (account *Account) Saved() (*SavedMedia, error) { body, err := account.inst.sendSimpleRequest(urlUserTags, account.ID) if err == nil { media := &SavedMedia{} err = json.Unmarshal(body, &media) return media, err } return nil, err }
[ "func", "(", "account", "*", "Account", ")", "Saved", "(", ")", "(", "*", "SavedMedia", ",", "error", ")", "{", "body", ",", "err", ":=", "account", ".", "inst", ".", "sendSimpleRequest", "(", "urlUserTags", ",", "account", ".", "ID", ")", "\n", "if", "err", "==", "nil", "{", "media", ":=", "&", "SavedMedia", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "media", ")", "\n", "return", "media", ",", "err", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// Saved returns saved media.
[ "Saved", "returns", "saved", "media", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/account.go#L312-L320
train
ahmdrz/goinsta
account.go
SetBiography
func (account *Account) SetBiography(bio string) error { account.edit() // preparing to edit insta := account.inst data, err := insta.prepareData( map[string]interface{}{ "raw_text": bio, }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSetBiography, Query: generateSignature(data), IsPost: true, }, ) if err == nil { var resp struct { User struct { Pk int64 `json:"pk"` Biography string `json:"biography"` } `json:"user"` Status string `json:"status"` } err = json.Unmarshal(body, &resp) if err == nil { account.Biography = resp.User.Biography } } return err }
go
func (account *Account) SetBiography(bio string) error { account.edit() // preparing to edit insta := account.inst data, err := insta.prepareData( map[string]interface{}{ "raw_text": bio, }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: urlSetBiography, Query: generateSignature(data), IsPost: true, }, ) if err == nil { var resp struct { User struct { Pk int64 `json:"pk"` Biography string `json:"biography"` } `json:"user"` Status string `json:"status"` } err = json.Unmarshal(body, &resp) if err == nil { account.Biography = resp.User.Biography } } return err }
[ "func", "(", "account", "*", "Account", ")", "SetBiography", "(", "bio", "string", ")", "error", "{", "account", ".", "edit", "(", ")", "\n", "insta", ":=", "account", ".", "inst", "\n", "data", ",", "err", ":=", "insta", ".", "prepareData", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"raw_text\"", ":", "bio", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlSetBiography", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "true", ",", "}", ",", ")", "\n", "if", "err", "==", "nil", "{", "var", "resp", "struct", "{", "User", "struct", "{", "Pk", "int64", "`json:\"pk\"`", "\n", "Biography", "string", "`json:\"biography\"`", "\n", "}", "`json:\"user\"`", "\n", "Status", "string", "`json:\"status\"`", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "if", "err", "==", "nil", "{", "account", ".", "Biography", "=", "resp", ".", "User", ".", "Biography", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SetBiography changes your Instagram's biography. // // This function updates current Account information.
[ "SetBiography", "changes", "your", "Instagram", "s", "biography", ".", "This", "function", "updates", "current", "Account", "information", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/account.go#L350-L383
train
ahmdrz/goinsta
account.go
Liked
func (account *Account) Liked() *FeedMedia { insta := account.inst media := &FeedMedia{} media.inst = insta media.endpoint = urlFeedLiked return media }
go
func (account *Account) Liked() *FeedMedia { insta := account.inst media := &FeedMedia{} media.inst = insta media.endpoint = urlFeedLiked return media }
[ "func", "(", "account", "*", "Account", ")", "Liked", "(", ")", "*", "FeedMedia", "{", "insta", ":=", "account", ".", "inst", "\n", "media", ":=", "&", "FeedMedia", "{", "}", "\n", "media", ".", "inst", "=", "insta", "\n", "media", ".", "endpoint", "=", "urlFeedLiked", "\n", "return", "media", "\n", "}" ]
// Liked are liked publications
[ "Liked", "are", "liked", "publications" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/account.go#L386-L393
train
ahmdrz/goinsta
account.go
PendingFollowRequests
func (account *Account) PendingFollowRequests() ([]User, error) { insta := account.inst resp, err := insta.sendRequest( &reqOptions{ Endpoint: urlFriendshipPending, }, ) if err != nil { return nil, err } var result struct { Users []User `json:"users"` // TODO: pagination // TODO: SuggestedUsers Status string `json:"status"` } err = json.Unmarshal(resp, &result) if err != nil { return nil, err } if result.Status != "ok" { return nil, fmt.Errorf("bad status: %s", result.Status) } return result.Users, nil }
go
func (account *Account) PendingFollowRequests() ([]User, error) { insta := account.inst resp, err := insta.sendRequest( &reqOptions{ Endpoint: urlFriendshipPending, }, ) if err != nil { return nil, err } var result struct { Users []User `json:"users"` // TODO: pagination // TODO: SuggestedUsers Status string `json:"status"` } err = json.Unmarshal(resp, &result) if err != nil { return nil, err } if result.Status != "ok" { return nil, fmt.Errorf("bad status: %s", result.Status) } return result.Users, nil }
[ "func", "(", "account", "*", "Account", ")", "PendingFollowRequests", "(", ")", "(", "[", "]", "User", ",", "error", ")", "{", "insta", ":=", "account", ".", "inst", "\n", "resp", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlFriendshipPending", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "result", "struct", "{", "Users", "[", "]", "User", "`json:\"users\"`", "\n", "Status", "string", "`json:\"status\"`", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "resp", ",", "&", "result", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "result", ".", "Status", "!=", "\"ok\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"bad status: %s\"", ",", "result", ".", "Status", ")", "\n", "}", "\n", "return", "result", ".", "Users", ",", "nil", "\n", "}" ]
// PendingFollowRequests returns pending follow requests.
[ "PendingFollowRequests", "returns", "pending", "follow", "requests", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/account.go#L396-L422
train
ahmdrz/goinsta
feeds.go
LocationID
func (feed *Feed) LocationID(locationID int64) (*FeedLocation, error) { insta := feed.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlFeedLocationID, locationID), Query: map[string]string{ "rank_token": insta.rankToken, "ranked_content": "true", }, }, ) if err != nil { return nil, err } res := &FeedLocation{} err = json.Unmarshal(body, res) return res, err }
go
func (feed *Feed) LocationID(locationID int64) (*FeedLocation, error) { insta := feed.inst body, err := insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlFeedLocationID, locationID), Query: map[string]string{ "rank_token": insta.rankToken, "ranked_content": "true", }, }, ) if err != nil { return nil, err } res := &FeedLocation{} err = json.Unmarshal(body, res) return res, err }
[ "func", "(", "feed", "*", "Feed", ")", "LocationID", "(", "locationID", "int64", ")", "(", "*", "FeedLocation", ",", "error", ")", "{", "insta", ":=", "feed", ".", "inst", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "fmt", ".", "Sprintf", "(", "urlFeedLocationID", ",", "locationID", ")", ",", "Query", ":", "map", "[", "string", "]", "string", "{", "\"rank_token\"", ":", "insta", ".", "rankToken", ",", "\"ranked_content\"", ":", "\"true\"", ",", "}", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "res", ":=", "&", "FeedLocation", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "res", ")", "\n", "return", "res", ",", "err", "\n", "}" ]
// Feed search by locationID
[ "Feed", "search", "by", "locationID" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/feeds.go#L21-L39
train
ahmdrz/goinsta
media.go
SyncLikers
func (item *Item) SyncLikers() error { resp := respLikers{} insta := item.media.instagram() body, err := insta.sendSimpleRequest(urlMediaLikers, item.ID) if err != nil { return err } err = json.Unmarshal(body, &resp) if err == nil { item.Likers = resp.Users } return err }
go
func (item *Item) SyncLikers() error { resp := respLikers{} insta := item.media.instagram() body, err := insta.sendSimpleRequest(urlMediaLikers, item.ID) if err != nil { return err } err = json.Unmarshal(body, &resp) if err == nil { item.Likers = resp.Users } return err }
[ "func", "(", "item", "*", "Item", ")", "SyncLikers", "(", ")", "error", "{", "resp", ":=", "respLikers", "{", "}", "\n", "insta", ":=", "item", ".", "media", ".", "instagram", "(", ")", "\n", "body", ",", "err", ":=", "insta", ".", "sendSimpleRequest", "(", "urlMediaLikers", ",", "item", ".", "ID", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "if", "err", "==", "nil", "{", "item", ".", "Likers", "=", "resp", ".", "Users", "\n", "}", "\n", "return", "err", "\n", "}" ]
// SyncLikers fetch new likers of a media // // This function updates Item.Likers value
[ "SyncLikers", "fetch", "new", "likers", "of", "a", "media", "This", "function", "updates", "Item", ".", "Likers", "value" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/media.go#L249-L261
train
ahmdrz/goinsta
media.go
ID
func (media *StoryMedia) ID() string { switch id := media.Pk.(type) { case int64: return strconv.FormatInt(id, 10) case string: return id } return "" }
go
func (media *StoryMedia) ID() string { switch id := media.Pk.(type) { case int64: return strconv.FormatInt(id, 10) case string: return id } return "" }
[ "func", "(", "media", "*", "StoryMedia", ")", "ID", "(", ")", "string", "{", "switch", "id", ":=", "media", ".", "Pk", ".", "(", "type", ")", "{", "case", "int64", ":", "return", "strconv", ".", "FormatInt", "(", "id", ",", "10", ")", "\n", "case", "string", ":", "return", "id", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// ID returns Story id
[ "ID", "returns", "Story", "id" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/media.go#L524-L532
train
ahmdrz/goinsta
media.go
Sync
func (media *StoryMedia) Sync() error { insta := media.inst query := []trayRequest{ {"SUPPORTED_SDK_VERSIONS", "9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0"}, {"FACE_TRACKER_VERSION", "10"}, {"segmentation", "segmentation_enabled"}, {"COMPRESSION", "ETC2_COMPRESSION"}, } qjson, err := json.Marshal(query) if err != nil { return err } id := media.Pk.(string) data, err := insta.prepareData( map[string]interface{}{ "user_ids": []string{id}, "supported_capabilities_new": b2s(qjson), }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: urlReelMedia, Query: generateSignature(data), IsPost: true, }, ) if err == nil { resp := trayResp{} err = json.Unmarshal(body, &resp) if err == nil { m, ok := resp.Reels[id] if ok { media.Items = m.Items media.setValues() return nil } err = fmt.Errorf("cannot find %s structure in response", id) } } return err }
go
func (media *StoryMedia) Sync() error { insta := media.inst query := []trayRequest{ {"SUPPORTED_SDK_VERSIONS", "9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0"}, {"FACE_TRACKER_VERSION", "10"}, {"segmentation", "segmentation_enabled"}, {"COMPRESSION", "ETC2_COMPRESSION"}, } qjson, err := json.Marshal(query) if err != nil { return err } id := media.Pk.(string) data, err := insta.prepareData( map[string]interface{}{ "user_ids": []string{id}, "supported_capabilities_new": b2s(qjson), }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: urlReelMedia, Query: generateSignature(data), IsPost: true, }, ) if err == nil { resp := trayResp{} err = json.Unmarshal(body, &resp) if err == nil { m, ok := resp.Reels[id] if ok { media.Items = m.Items media.setValues() return nil } err = fmt.Errorf("cannot find %s structure in response", id) } } return err }
[ "func", "(", "media", "*", "StoryMedia", ")", "Sync", "(", ")", "error", "{", "insta", ":=", "media", ".", "inst", "\n", "query", ":=", "[", "]", "trayRequest", "{", "{", "\"SUPPORTED_SDK_VERSIONS\"", ",", "\"9.0,10.0,11.0,12.0,13.0,14.0,15.0,16.0,17.0,18.0,19.0,20.0,21.0,22.0,23.0,24.0\"", "}", ",", "{", "\"FACE_TRACKER_VERSION\"", ",", "\"10\"", "}", ",", "{", "\"segmentation\"", ",", "\"segmentation_enabled\"", "}", ",", "{", "\"COMPRESSION\"", ",", "\"ETC2_COMPRESSION\"", "}", ",", "}", "\n", "qjson", ",", "err", ":=", "json", ".", "Marshal", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "id", ":=", "media", ".", "Pk", ".", "(", "string", ")", "\n", "data", ",", "err", ":=", "insta", ".", "prepareData", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"user_ids\"", ":", "[", "]", "string", "{", "id", "}", ",", "\"supported_capabilities_new\"", ":", "b2s", "(", "qjson", ")", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "urlReelMedia", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "true", ",", "}", ",", ")", "\n", "if", "err", "==", "nil", "{", "resp", ":=", "trayResp", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "if", "err", "==", "nil", "{", "m", ",", "ok", ":=", "resp", ".", "Reels", "[", "id", "]", "\n", "if", "ok", "{", "media", ".", "Items", "=", "m", ".", "Items", "\n", "media", ".", "setValues", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "err", "=", "fmt", ".", "Errorf", "(", "\"cannot find %s structure in response\"", ",", "id", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Sync function is used when Highlight must be sync. // Highlight must be sync when User.Highlights does not return any object inside StoryMedia slice. // // This function does NOT update Stories items. // // This function updates StoryMedia.Items
[ "Sync", "function", "is", "used", "when", "Highlight", "must", "be", "sync", ".", "Highlight", "must", "be", "sync", "when", "User", ".", "Highlights", "does", "not", "return", "any", "object", "inside", "StoryMedia", "slice", ".", "This", "function", "does", "NOT", "update", "Stories", "items", ".", "This", "function", "updates", "StoryMedia", ".", "Items" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/media.go#L589-L634
train
ahmdrz/goinsta
media.go
Sync
func (media *FeedMedia) Sync() error { id := media.ID() insta := media.inst data, err := insta.prepareData( map[string]interface{}{ "media_id": id, }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlMediaInfo, id), Query: generateSignature(data), IsPost: false, }, ) if err != nil { return err } m := FeedMedia{} err = json.Unmarshal(body, &m) *media = m media.endpoint = urlMediaInfo media.inst = insta media.NextID = id media.setValues() return err }
go
func (media *FeedMedia) Sync() error { id := media.ID() insta := media.inst data, err := insta.prepareData( map[string]interface{}{ "media_id": id, }, ) if err != nil { return err } body, err := insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlMediaInfo, id), Query: generateSignature(data), IsPost: false, }, ) if err != nil { return err } m := FeedMedia{} err = json.Unmarshal(body, &m) *media = m media.endpoint = urlMediaInfo media.inst = insta media.NextID = id media.setValues() return err }
[ "func", "(", "media", "*", "FeedMedia", ")", "Sync", "(", ")", "error", "{", "id", ":=", "media", ".", "ID", "(", ")", "\n", "insta", ":=", "media", ".", "inst", "\n", "data", ",", "err", ":=", "insta", ".", "prepareData", "(", "map", "[", "string", "]", "interface", "{", "}", "{", "\"media_id\"", ":", "id", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "fmt", ".", "Sprintf", "(", "urlMediaInfo", ",", "id", ")", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "false", ",", "}", ",", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "m", ":=", "FeedMedia", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "m", ")", "\n", "*", "media", "=", "m", "\n", "media", ".", "endpoint", "=", "urlMediaInfo", "\n", "media", ".", "inst", "=", "insta", "\n", "media", ".", "NextID", "=", "id", "\n", "media", ".", "setValues", "(", ")", "\n", "return", "err", "\n", "}" ]
// Sync updates media values.
[ "Sync", "updates", "media", "values", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/media.go#L717-L749
train
ahmdrz/goinsta
media.go
ID
func (media *FeedMedia) ID() string { switch s := media.NextID.(type) { case string: return s case int64: return strconv.FormatInt(s, 10) case json.Number: return string(s) } return "" }
go
func (media *FeedMedia) ID() string { switch s := media.NextID.(type) { case string: return s case int64: return strconv.FormatInt(s, 10) case json.Number: return string(s) } return "" }
[ "func", "(", "media", "*", "FeedMedia", ")", "ID", "(", ")", "string", "{", "switch", "s", ":=", "media", ".", "NextID", ".", "(", "type", ")", "{", "case", "string", ":", "return", "s", "\n", "case", "int64", ":", "return", "strconv", ".", "FormatInt", "(", "s", ",", "10", ")", "\n", "case", "json", ".", "Number", ":", "return", "string", "(", "s", ")", "\n", "}", "\n", "return", "\"\"", "\n", "}" ]
// ID returns media id.
[ "ID", "returns", "media", "id", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/media.go#L762-L772
train
ahmdrz/goinsta
inbox.go
Write
func (c *Conversation) Write(b []byte) (int, error) { n := len(b) return n, c.Send(b2s(b)) }
go
func (c *Conversation) Write(b []byte) (int, error) { n := len(b) return n, c.Send(b2s(b)) }
[ "func", "(", "c", "*", "Conversation", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ":=", "len", "(", "b", ")", "\n", "return", "n", ",", "c", ".", "Send", "(", "b2s", "(", "b", ")", ")", "\n", "}" ]
// Write is like Send but being compatible with io.Writer.
[ "Write", "is", "like", "Send", "but", "being", "compatible", "with", "io", ".", "Writer", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/inbox.go#L340-L343
train
ahmdrz/goinsta
comments.go
Next
func (comments *Comments) Next() bool { if comments.err != nil { return false } item := comments.item insta := item.media.instagram() endpoint := comments.endpoint query := map[string]string{ // "can_support_threading": "true", } if comments.NextMaxID != nil { next, _ := strconv.Unquote(string(comments.NextMaxID)) query["max_id"] = next } else if comments.NextMinID != nil { next, _ := strconv.Unquote(string(comments.NextMinID)) query["min_id"] = next } body, err := insta.sendRequest( &reqOptions{ Endpoint: endpoint, Connection: "keep-alive", Query: query, }, ) if err == nil { c := Comments{} err = json.Unmarshal(body, &c) if err == nil { *comments = c comments.endpoint = endpoint comments.item = item if (!comments.HasMoreComments || comments.NextMaxID == nil) && (!comments.HasMoreHeadloadComments || comments.NextMinID == nil) { comments.err = ErrNoMore } comments.setValues() return true } } comments.err = err return false }
go
func (comments *Comments) Next() bool { if comments.err != nil { return false } item := comments.item insta := item.media.instagram() endpoint := comments.endpoint query := map[string]string{ // "can_support_threading": "true", } if comments.NextMaxID != nil { next, _ := strconv.Unquote(string(comments.NextMaxID)) query["max_id"] = next } else if comments.NextMinID != nil { next, _ := strconv.Unquote(string(comments.NextMinID)) query["min_id"] = next } body, err := insta.sendRequest( &reqOptions{ Endpoint: endpoint, Connection: "keep-alive", Query: query, }, ) if err == nil { c := Comments{} err = json.Unmarshal(body, &c) if err == nil { *comments = c comments.endpoint = endpoint comments.item = item if (!comments.HasMoreComments || comments.NextMaxID == nil) && (!comments.HasMoreHeadloadComments || comments.NextMinID == nil) { comments.err = ErrNoMore } comments.setValues() return true } } comments.err = err return false }
[ "func", "(", "comments", "*", "Comments", ")", "Next", "(", ")", "bool", "{", "if", "comments", ".", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "item", ":=", "comments", ".", "item", "\n", "insta", ":=", "item", ".", "media", ".", "instagram", "(", ")", "\n", "endpoint", ":=", "comments", ".", "endpoint", "\n", "query", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "if", "comments", ".", "NextMaxID", "!=", "nil", "{", "next", ",", "_", ":=", "strconv", ".", "Unquote", "(", "string", "(", "comments", ".", "NextMaxID", ")", ")", "\n", "query", "[", "\"max_id\"", "]", "=", "next", "\n", "}", "else", "if", "comments", ".", "NextMinID", "!=", "nil", "{", "next", ",", "_", ":=", "strconv", ".", "Unquote", "(", "string", "(", "comments", ".", "NextMinID", ")", ")", "\n", "query", "[", "\"min_id\"", "]", "=", "next", "\n", "}", "\n", "body", ",", "err", ":=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "endpoint", ",", "Connection", ":", "\"keep-alive\"", ",", "Query", ":", "query", ",", "}", ",", ")", "\n", "if", "err", "==", "nil", "{", "c", ":=", "Comments", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "c", ")", "\n", "if", "err", "==", "nil", "{", "*", "comments", "=", "c", "\n", "comments", ".", "endpoint", "=", "endpoint", "\n", "comments", ".", "item", "=", "item", "\n", "if", "(", "!", "comments", ".", "HasMoreComments", "||", "comments", ".", "NextMaxID", "==", "nil", ")", "&&", "(", "!", "comments", ".", "HasMoreHeadloadComments", "||", "comments", ".", "NextMinID", "==", "nil", ")", "{", "comments", ".", "err", "=", "ErrNoMore", "\n", "}", "\n", "comments", ".", "setValues", "(", ")", "\n", "return", "true", "\n", "}", "\n", "}", "\n", "comments", ".", "err", "=", "err", "\n", "return", "false", "\n", "}" ]
// Next allows comment pagination. // // This function support concurrency methods to get comments using Last and Next ID // // New comments are stored in Comments.Items
[ "Next", "allows", "comment", "pagination", ".", "This", "function", "support", "concurrency", "methods", "to", "get", "comments", "using", "Last", "and", "Next", "ID", "New", "comments", "are", "stored", "in", "Comments", ".", "Items" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/comments.go#L117-L160
train
ahmdrz/goinsta
comments.go
Del
func (comments *Comments) Del(comment *Comment) error { insta := comments.item.media.instagram() data, err := insta.prepareData() if err != nil { return err } id := comment.getid() _, err = insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlCommentDelete, comments.item.ID, id), Query: generateSignature(data), IsPost: true, }, ) return err }
go
func (comments *Comments) Del(comment *Comment) error { insta := comments.item.media.instagram() data, err := insta.prepareData() if err != nil { return err } id := comment.getid() _, err = insta.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlCommentDelete, comments.item.ID, id), Query: generateSignature(data), IsPost: true, }, ) return err }
[ "func", "(", "comments", "*", "Comments", ")", "Del", "(", "comment", "*", "Comment", ")", "error", "{", "insta", ":=", "comments", ".", "item", ".", "media", ".", "instagram", "(", ")", "\n", "data", ",", "err", ":=", "insta", ".", "prepareData", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "id", ":=", "comment", ".", "getid", "(", ")", "\n", "_", ",", "err", "=", "insta", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "fmt", ".", "Sprintf", "(", "urlCommentDelete", ",", "comments", ".", "item", ".", "ID", ",", "id", ")", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "true", ",", "}", ",", ")", "\n", "return", "err", "\n", "}" ]
// Del deletes comment.
[ "Del", "deletes", "comment", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/comments.go#L230-L247
train
ahmdrz/goinsta
comments.go
Like
func (c *Comment) Like() error { data, err := c.inst.prepareData() if err != nil { return err } _, err = c.inst.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlCommentLike, c.getid()), Query: generateSignature(data), IsPost: true, }, ) return err }
go
func (c *Comment) Like() error { data, err := c.inst.prepareData() if err != nil { return err } _, err = c.inst.sendRequest( &reqOptions{ Endpoint: fmt.Sprintf(urlCommentLike, c.getid()), Query: generateSignature(data), IsPost: true, }, ) return err }
[ "func", "(", "c", "*", "Comment", ")", "Like", "(", ")", "error", "{", "data", ",", "err", ":=", "c", ".", "inst", ".", "prepareData", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "c", ".", "inst", ".", "sendRequest", "(", "&", "reqOptions", "{", "Endpoint", ":", "fmt", ".", "Sprintf", "(", "urlCommentLike", ",", "c", ".", "getid", "(", ")", ")", ",", "Query", ":", "generateSignature", "(", "data", ")", ",", "IsPost", ":", "true", ",", "}", ",", ")", "\n", "return", "err", "\n", "}" ]
// Like likes comment.
[ "Like", "likes", "comment", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/comments.go#L339-L353
train
ahmdrz/goinsta
hashtags.go
NewHashtag
func (inst *Instagram) NewHashtag(name string) *Hashtag { return &Hashtag{ inst: inst, Name: name, } }
go
func (inst *Instagram) NewHashtag(name string) *Hashtag { return &Hashtag{ inst: inst, Name: name, } }
[ "func", "(", "inst", "*", "Instagram", ")", "NewHashtag", "(", "name", "string", ")", "*", "Hashtag", "{", "return", "&", "Hashtag", "{", "inst", ":", "inst", ",", "Name", ":", "name", ",", "}", "\n", "}" ]
// NewHashtag returns initialised hashtag structure // Name parameter is hashtag name
[ "NewHashtag", "returns", "initialised", "hashtag", "structure", "Name", "parameter", "is", "hashtag", "name" ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/hashtags.go#L56-L61
train
ahmdrz/goinsta
hashtags.go
Sync
func (h *Hashtag) Sync() error { insta := h.inst body, err := insta.sendSimpleRequest(urlTagSync, h.Name) if err == nil { var resp struct { Name string `json:"name"` ID int64 `json:"id"` MediaCount int `json:"media_count"` } err = json.Unmarshal(body, &resp) if err == nil { h.Name = resp.Name h.ID = resp.ID h.MediaCount = resp.MediaCount h.setValues() } } return err }
go
func (h *Hashtag) Sync() error { insta := h.inst body, err := insta.sendSimpleRequest(urlTagSync, h.Name) if err == nil { var resp struct { Name string `json:"name"` ID int64 `json:"id"` MediaCount int `json:"media_count"` } err = json.Unmarshal(body, &resp) if err == nil { h.Name = resp.Name h.ID = resp.ID h.MediaCount = resp.MediaCount h.setValues() } } return err }
[ "func", "(", "h", "*", "Hashtag", ")", "Sync", "(", ")", "error", "{", "insta", ":=", "h", ".", "inst", "\n", "body", ",", "err", ":=", "insta", ".", "sendSimpleRequest", "(", "urlTagSync", ",", "h", ".", "Name", ")", "\n", "if", "err", "==", "nil", "{", "var", "resp", "struct", "{", "Name", "string", "`json:\"name\"`", "\n", "ID", "int64", "`json:\"id\"`", "\n", "MediaCount", "int", "`json:\"media_count\"`", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "if", "err", "==", "nil", "{", "h", ".", "Name", "=", "resp", ".", "Name", "\n", "h", ".", "ID", "=", "resp", ".", "ID", "\n", "h", ".", "MediaCount", "=", "resp", ".", "MediaCount", "\n", "h", ".", "setValues", "(", ")", "\n", "}", "\n", "}", "\n", "return", "err", "\n", "}" ]
// Sync updates Hashtag information preparing it to Next call.
[ "Sync", "updates", "Hashtag", "information", "preparing", "it", "to", "Next", "call", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/hashtags.go#L64-L83
train
ahmdrz/goinsta
hashtags.go
Stories
func (h *Hashtag) Stories() (*StoryMedia, error) { body, err := h.inst.sendSimpleRequest( urlTagStories, h.Name, ) if err == nil { var resp struct { Story StoryMedia `json:"story"` Status string `json:"status"` } err = json.Unmarshal(body, &resp) return &resp.Story, err } return nil, err }
go
func (h *Hashtag) Stories() (*StoryMedia, error) { body, err := h.inst.sendSimpleRequest( urlTagStories, h.Name, ) if err == nil { var resp struct { Story StoryMedia `json:"story"` Status string `json:"status"` } err = json.Unmarshal(body, &resp) return &resp.Story, err } return nil, err }
[ "func", "(", "h", "*", "Hashtag", ")", "Stories", "(", ")", "(", "*", "StoryMedia", ",", "error", ")", "{", "body", ",", "err", ":=", "h", ".", "inst", ".", "sendSimpleRequest", "(", "urlTagStories", ",", "h", ".", "Name", ",", ")", "\n", "if", "err", "==", "nil", "{", "var", "resp", "struct", "{", "Story", "StoryMedia", "`json:\"story\"`", "\n", "Status", "string", "`json:\"status\"`", "\n", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "return", "&", "resp", ".", "Story", ",", "err", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// Stories returns hashtag stories.
[ "Stories", "returns", "hashtag", "stories", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/hashtags.go#L127-L140
train
ahmdrz/goinsta
profiles.go
Blocked
func (prof *Profiles) Blocked() ([]BlockedUser, error) { body, err := prof.inst.sendSimpleRequest(urlBlockedList) if err == nil { resp := blockedListResp{} err = json.Unmarshal(body, &resp) return resp.BlockedList, err } return nil, err }
go
func (prof *Profiles) Blocked() ([]BlockedUser, error) { body, err := prof.inst.sendSimpleRequest(urlBlockedList) if err == nil { resp := blockedListResp{} err = json.Unmarshal(body, &resp) return resp.BlockedList, err } return nil, err }
[ "func", "(", "prof", "*", "Profiles", ")", "Blocked", "(", ")", "(", "[", "]", "BlockedUser", ",", "error", ")", "{", "body", ",", "err", ":=", "prof", ".", "inst", ".", "sendSimpleRequest", "(", "urlBlockedList", ")", "\n", "if", "err", "==", "nil", "{", "resp", ":=", "blockedListResp", "{", "}", "\n", "err", "=", "json", ".", "Unmarshal", "(", "body", ",", "&", "resp", ")", "\n", "return", "resp", ".", "BlockedList", ",", "err", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}" ]
// Blocked returns a list of blocked profiles.
[ "Blocked", "returns", "a", "list", "of", "blocked", "profiles", "." ]
86d8297fa4152941d864ca6d7d2e1f1f673708aa
https://github.com/ahmdrz/goinsta/blob/86d8297fa4152941d864ca6d7d2e1f1f673708aa/profiles.go#L61-L69
train
mailru/easyjson
opt/gotemplate_Uint64.go
MarshalJSON
func (v Uint64) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error }
go
func (v Uint64) MarshalJSON() ([]byte, error) { w := jwriter.Writer{} v.MarshalEasyJSON(&w) return w.Buffer.BuildBytes(), w.Error }
[ "func", "(", "v", "Uint64", ")", "MarshalJSON", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "w", ":=", "jwriter", ".", "Writer", "{", "}", "\n", "v", ".", "MarshalEasyJSON", "(", "&", "w", ")", "\n", "return", "w", ".", "Buffer", ".", "BuildBytes", "(", ")", ",", "w", ".", "Error", "\n", "}" ]
// MarshalJSON implements a standard json marshaler interface.
[ "MarshalJSON", "implements", "a", "standard", "json", "marshaler", "interface", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/opt/gotemplate_Uint64.go#L54-L58
train
mailru/easyjson
opt/gotemplate_Uint64.go
UnmarshalJSON
func (v *Uint64) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() }
go
func (v *Uint64) UnmarshalJSON(data []byte) error { l := jlexer.Lexer{Data: data} v.UnmarshalEasyJSON(&l) return l.Error() }
[ "func", "(", "v", "*", "Uint64", ")", "UnmarshalJSON", "(", "data", "[", "]", "byte", ")", "error", "{", "l", ":=", "jlexer", ".", "Lexer", "{", "Data", ":", "data", "}", "\n", "v", ".", "UnmarshalEasyJSON", "(", "&", "l", ")", "\n", "return", "l", ".", "Error", "(", ")", "\n", "}" ]
// UnmarshalJSON implements a standard json unmarshaler interface.
[ "UnmarshalJSON", "implements", "a", "standard", "json", "unmarshaler", "interface", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/opt/gotemplate_Uint64.go#L61-L65
train
mailru/easyjson
gen/decoder.go
genTypeDecoder
func (g *Generator) genTypeDecoder(t reflect.Type, out string, tags fieldTags, indent int) error { ws := strings.Repeat(" ", indent) unmarshalerIface := reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"("+out+").UnmarshalEasyJSON(in)") return nil } unmarshalerIface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.Raw(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalJSON(data) )") fmt.Fprintln(g.out, ws+"}") return nil } unmarshalerIface = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.UnsafeBytes(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalText(data) )") fmt.Fprintln(g.out, ws+"}") return nil } err := g.genTypeDecoderNoCheck(t, out, tags, indent) return err }
go
func (g *Generator) genTypeDecoder(t reflect.Type, out string, tags fieldTags, indent int) error { ws := strings.Repeat(" ", indent) unmarshalerIface := reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"("+out+").UnmarshalEasyJSON(in)") return nil } unmarshalerIface = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.Raw(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalJSON(data) )") fmt.Fprintln(g.out, ws+"}") return nil } unmarshalerIface = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(unmarshalerIface) { fmt.Fprintln(g.out, ws+"if data := in.UnsafeBytes(); in.Ok() {") fmt.Fprintln(g.out, ws+" in.AddError( ("+out+").UnmarshalText(data) )") fmt.Fprintln(g.out, ws+"}") return nil } err := g.genTypeDecoderNoCheck(t, out, tags, indent) return err }
[ "func", "(", "g", "*", "Generator", ")", "genTypeDecoder", "(", "t", "reflect", ".", "Type", ",", "out", "string", ",", "tags", "fieldTags", ",", "indent", "int", ")", "error", "{", "ws", ":=", "strings", ".", "Repeat", "(", "\" \"", ",", "indent", ")", "\n", "unmarshalerIface", ":=", "reflect", ".", "TypeOf", "(", "(", "*", "easyjson", ".", "Unmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "unmarshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"(\"", "+", "out", "+", "\").UnmarshalEasyJSON(in)\"", ")", "\n", "return", "nil", "\n", "}", "\n", "unmarshalerIface", "=", "reflect", ".", "TypeOf", "(", "(", "*", "json", ".", "Unmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "unmarshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"if data := in.Raw(); in.Ok() {\"", ")", "\n", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\" in.AddError( (\"", "+", "out", "+", "\").UnmarshalJSON(data) )\"", ")", "\n", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"}\"", ")", "\n", "return", "nil", "\n", "}", "\n", "unmarshalerIface", "=", "reflect", ".", "TypeOf", "(", "(", "*", "encoding", ".", "TextUnmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "unmarshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"if data := in.UnsafeBytes(); in.Ok() {\"", ")", "\n", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\" in.AddError( (\"", "+", "out", "+", "\").UnmarshalText(data) )\"", ")", "\n", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"}\"", ")", "\n", "return", "nil", "\n", "}", "\n", "err", ":=", "g", ".", "genTypeDecoderNoCheck", "(", "t", ",", "out", ",", "tags", ",", "indent", ")", "\n", "return", "err", "\n", "}" ]
// genTypeDecoder generates decoding code for the type t, but uses unmarshaler interface if implemented by t.
[ "genTypeDecoder", "generates", "decoding", "code", "for", "the", "type", "t", "but", "uses", "unmarshaler", "interface", "if", "implemented", "by", "t", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/decoder.go#L60-L87
train
mailru/easyjson
gen/decoder.go
hasCustomUnmarshaler
func hasCustomUnmarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()) }
go
func hasCustomUnmarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()) }
[ "func", "hasCustomUnmarshaler", "(", "t", "reflect", ".", "Type", ")", "bool", "{", "t", "=", "reflect", ".", "PtrTo", "(", "t", ")", "\n", "return", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "easyjson", ".", "Unmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "||", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "json", ".", "Unmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "||", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "encoding", ".", "TextUnmarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "\n", "}" ]
// returns true of the type t implements one of the custom unmarshaler interfaces
[ "returns", "true", "of", "the", "type", "t", "implements", "one", "of", "the", "custom", "unmarshaler", "interfaces" ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/decoder.go#L90-L95
train
mailru/easyjson
opt/gotemplate_Float32.go
String
func (v Float32) String() string { if !v.Defined { return "<undefined>" } return fmt.Sprint(v.V) }
go
func (v Float32) String() string { if !v.Defined { return "<undefined>" } return fmt.Sprint(v.V) }
[ "func", "(", "v", "Float32", ")", "String", "(", ")", "string", "{", "if", "!", "v", ".", "Defined", "{", "return", "\"<undefined>\"", "\n", "}", "\n", "return", "fmt", ".", "Sprint", "(", "v", ".", "V", ")", "\n", "}" ]
// String implements a stringer interface using fmt.Sprint for the value.
[ "String", "implements", "a", "stringer", "interface", "using", "fmt", ".", "Sprint", "for", "the", "value", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/opt/gotemplate_Float32.go#L74-L79
train
mailru/easyjson
gen/generator.go
NewGenerator
func NewGenerator(filename string) *Generator { ret := &Generator{ imports: map[string]string{ pkgWriter: "jwriter", pkgLexer: "jlexer", pkgEasyJSON: "easyjson", "encoding/json": "json", }, fieldNamer: DefaultFieldNamer{}, marshalers: make(map[reflect.Type]bool), typesSeen: make(map[reflect.Type]bool), functionNames: make(map[string]reflect.Type), } // Use a file-unique prefix on all auxiliary funcs to avoid // name clashes. hash := fnv.New32() hash.Write([]byte(filename)) ret.hashString = fmt.Sprintf("%x", hash.Sum32()) return ret }
go
func NewGenerator(filename string) *Generator { ret := &Generator{ imports: map[string]string{ pkgWriter: "jwriter", pkgLexer: "jlexer", pkgEasyJSON: "easyjson", "encoding/json": "json", }, fieldNamer: DefaultFieldNamer{}, marshalers: make(map[reflect.Type]bool), typesSeen: make(map[reflect.Type]bool), functionNames: make(map[string]reflect.Type), } // Use a file-unique prefix on all auxiliary funcs to avoid // name clashes. hash := fnv.New32() hash.Write([]byte(filename)) ret.hashString = fmt.Sprintf("%x", hash.Sum32()) return ret }
[ "func", "NewGenerator", "(", "filename", "string", ")", "*", "Generator", "{", "ret", ":=", "&", "Generator", "{", "imports", ":", "map", "[", "string", "]", "string", "{", "pkgWriter", ":", "\"jwriter\"", ",", "pkgLexer", ":", "\"jlexer\"", ",", "pkgEasyJSON", ":", "\"easyjson\"", ",", "\"encoding/json\"", ":", "\"json\"", ",", "}", ",", "fieldNamer", ":", "DefaultFieldNamer", "{", "}", ",", "marshalers", ":", "make", "(", "map", "[", "reflect", ".", "Type", "]", "bool", ")", ",", "typesSeen", ":", "make", "(", "map", "[", "reflect", ".", "Type", "]", "bool", ")", ",", "functionNames", ":", "make", "(", "map", "[", "string", "]", "reflect", ".", "Type", ")", ",", "}", "\n", "hash", ":=", "fnv", ".", "New32", "(", ")", "\n", "hash", ".", "Write", "(", "[", "]", "byte", "(", "filename", ")", ")", "\n", "ret", ".", "hashString", "=", "fmt", ".", "Sprintf", "(", "\"%x\"", ",", "hash", ".", "Sum32", "(", ")", ")", "\n", "return", "ret", "\n", "}" ]
// NewGenerator initializes and returns a Generator.
[ "NewGenerator", "initializes", "and", "returns", "a", "Generator", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L59-L80
train
mailru/easyjson
gen/generator.go
SetPkg
func (g *Generator) SetPkg(name, path string) { g.pkgName = name g.pkgPath = path }
go
func (g *Generator) SetPkg(name, path string) { g.pkgName = name g.pkgPath = path }
[ "func", "(", "g", "*", "Generator", ")", "SetPkg", "(", "name", ",", "path", "string", ")", "{", "g", ".", "pkgName", "=", "name", "\n", "g", ".", "pkgPath", "=", "path", "\n", "}" ]
// SetPkg sets the name and path of output package.
[ "SetPkg", "sets", "the", "name", "and", "path", "of", "output", "package", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L83-L86
train
mailru/easyjson
gen/generator.go
printHeader
func (g *Generator) printHeader() { if g.buildTags != "" { fmt.Println("// +build ", g.buildTags) fmt.Println() } fmt.Println("// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.") fmt.Println() fmt.Println("package ", g.pkgName) fmt.Println() byAlias := map[string]string{} var aliases []string for path, alias := range g.imports { aliases = append(aliases, alias) byAlias[alias] = path } sort.Strings(aliases) fmt.Println("import (") for _, alias := range aliases { fmt.Printf(" %s %q\n", alias, byAlias[alias]) } fmt.Println(")") fmt.Println("") fmt.Println("// suppress unused package warning") fmt.Println("var (") fmt.Println(" _ *json.RawMessage") fmt.Println(" _ *jlexer.Lexer") fmt.Println(" _ *jwriter.Writer") fmt.Println(" _ easyjson.Marshaler") fmt.Println(")") fmt.Println() }
go
func (g *Generator) printHeader() { if g.buildTags != "" { fmt.Println("// +build ", g.buildTags) fmt.Println() } fmt.Println("// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.") fmt.Println() fmt.Println("package ", g.pkgName) fmt.Println() byAlias := map[string]string{} var aliases []string for path, alias := range g.imports { aliases = append(aliases, alias) byAlias[alias] = path } sort.Strings(aliases) fmt.Println("import (") for _, alias := range aliases { fmt.Printf(" %s %q\n", alias, byAlias[alias]) } fmt.Println(")") fmt.Println("") fmt.Println("// suppress unused package warning") fmt.Println("var (") fmt.Println(" _ *json.RawMessage") fmt.Println(" _ *jlexer.Lexer") fmt.Println(" _ *jwriter.Writer") fmt.Println(" _ easyjson.Marshaler") fmt.Println(")") fmt.Println() }
[ "func", "(", "g", "*", "Generator", ")", "printHeader", "(", ")", "{", "if", "g", ".", "buildTags", "!=", "\"\"", "{", "fmt", ".", "Println", "(", "\"// +build \"", ",", "g", ".", "buildTags", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "}", "\n", "fmt", ".", "Println", "(", "\"// Code generated by easyjson for marshaling/unmarshaling. DO NOT EDIT.\"", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "fmt", ".", "Println", "(", "\"package \"", ",", "g", ".", "pkgName", ")", "\n", "fmt", ".", "Println", "(", ")", "\n", "byAlias", ":=", "map", "[", "string", "]", "string", "{", "}", "\n", "var", "aliases", "[", "]", "string", "\n", "for", "path", ",", "alias", ":=", "range", "g", ".", "imports", "{", "aliases", "=", "append", "(", "aliases", ",", "alias", ")", "\n", "byAlias", "[", "alias", "]", "=", "path", "\n", "}", "\n", "sort", ".", "Strings", "(", "aliases", ")", "\n", "fmt", ".", "Println", "(", "\"import (\"", ")", "\n", "for", "_", ",", "alias", ":=", "range", "aliases", "{", "fmt", ".", "Printf", "(", "\" %s %q\\n\"", ",", "\\n", ",", "alias", ")", "\n", "}", "\n", "byAlias", "[", "alias", "]", "\n", "fmt", ".", "Println", "(", "\")\"", ")", "\n", "fmt", ".", "Println", "(", "\"\"", ")", "\n", "fmt", ".", "Println", "(", "\"// suppress unused package warning\"", ")", "\n", "fmt", ".", "Println", "(", "\"var (\"", ")", "\n", "fmt", ".", "Println", "(", "\" _ *json.RawMessage\"", ")", "\n", "fmt", ".", "Println", "(", "\" _ *jlexer.Lexer\"", ")", "\n", "fmt", ".", "Println", "(", "\" _ *jwriter.Writer\"", ")", "\n", "fmt", ".", "Println", "(", "\" _ easyjson.Marshaler\"", ")", "\n", "fmt", ".", "Println", "(", "\")\"", ")", "\n", "}" ]
// printHeader prints package declaration and imports.
[ "printHeader", "prints", "package", "declaration", "and", "imports", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L149-L183
train
mailru/easyjson
gen/generator.go
Run
func (g *Generator) Run(out io.Writer) error { g.out = &bytes.Buffer{} for len(g.typesUnseen) > 0 { t := g.typesUnseen[len(g.typesUnseen)-1] g.typesUnseen = g.typesUnseen[:len(g.typesUnseen)-1] g.typesSeen[t] = true if err := g.genDecoder(t); err != nil { return err } if err := g.genEncoder(t); err != nil { return err } if !g.marshalers[t] { continue } if err := g.genStructMarshaler(t); err != nil { return err } if err := g.genStructUnmarshaler(t); err != nil { return err } } g.printHeader() _, err := out.Write(g.out.Bytes()) return err }
go
func (g *Generator) Run(out io.Writer) error { g.out = &bytes.Buffer{} for len(g.typesUnseen) > 0 { t := g.typesUnseen[len(g.typesUnseen)-1] g.typesUnseen = g.typesUnseen[:len(g.typesUnseen)-1] g.typesSeen[t] = true if err := g.genDecoder(t); err != nil { return err } if err := g.genEncoder(t); err != nil { return err } if !g.marshalers[t] { continue } if err := g.genStructMarshaler(t); err != nil { return err } if err := g.genStructUnmarshaler(t); err != nil { return err } } g.printHeader() _, err := out.Write(g.out.Bytes()) return err }
[ "func", "(", "g", "*", "Generator", ")", "Run", "(", "out", "io", ".", "Writer", ")", "error", "{", "g", ".", "out", "=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "for", "len", "(", "g", ".", "typesUnseen", ")", ">", "0", "{", "t", ":=", "g", ".", "typesUnseen", "[", "len", "(", "g", ".", "typesUnseen", ")", "-", "1", "]", "\n", "g", ".", "typesUnseen", "=", "g", ".", "typesUnseen", "[", ":", "len", "(", "g", ".", "typesUnseen", ")", "-", "1", "]", "\n", "g", ".", "typesSeen", "[", "t", "]", "=", "true", "\n", "if", "err", ":=", "g", ".", "genDecoder", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "g", ".", "genEncoder", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "g", ".", "marshalers", "[", "t", "]", "{", "continue", "\n", "}", "\n", "if", "err", ":=", "g", ".", "genStructMarshaler", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "g", ".", "genStructUnmarshaler", "(", "t", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "g", ".", "printHeader", "(", ")", "\n", "_", ",", "err", ":=", "out", ".", "Write", "(", "g", ".", "out", ".", "Bytes", "(", ")", ")", "\n", "return", "err", "\n", "}" ]
// Run runs the generator and outputs generated code to out.
[ "Run", "runs", "the", "generator", "and", "outputs", "generated", "code", "to", "out", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L186-L215
train
mailru/easyjson
gen/generator.go
fixPkgPathVendoring
func fixPkgPathVendoring(pkgPath string) string { const vendor = "/vendor/" if i := strings.LastIndex(pkgPath, vendor); i != -1 { return pkgPath[i+len(vendor):] } return pkgPath }
go
func fixPkgPathVendoring(pkgPath string) string { const vendor = "/vendor/" if i := strings.LastIndex(pkgPath, vendor); i != -1 { return pkgPath[i+len(vendor):] } return pkgPath }
[ "func", "fixPkgPathVendoring", "(", "pkgPath", "string", ")", "string", "{", "const", "vendor", "=", "\"/vendor/\"", "\n", "if", "i", ":=", "strings", ".", "LastIndex", "(", "pkgPath", ",", "vendor", ")", ";", "i", "!=", "-", "1", "{", "return", "pkgPath", "[", "i", "+", "len", "(", "vendor", ")", ":", "]", "\n", "}", "\n", "return", "pkgPath", "\n", "}" ]
// fixes vendored paths
[ "fixes", "vendored", "paths" ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L218-L224
train
mailru/easyjson
gen/generator.go
pkgAlias
func (g *Generator) pkgAlias(pkgPath string) string { pkgPath = fixPkgPathVendoring(pkgPath) if alias := g.imports[pkgPath]; alias != "" { return alias } for i := 0; ; i++ { alias := fixAliasName(path.Base(pkgPath)) if i > 0 { alias += fmt.Sprint(i) } exists := false for _, v := range g.imports { if v == alias { exists = true break } } if !exists { g.imports[pkgPath] = alias return alias } } }
go
func (g *Generator) pkgAlias(pkgPath string) string { pkgPath = fixPkgPathVendoring(pkgPath) if alias := g.imports[pkgPath]; alias != "" { return alias } for i := 0; ; i++ { alias := fixAliasName(path.Base(pkgPath)) if i > 0 { alias += fmt.Sprint(i) } exists := false for _, v := range g.imports { if v == alias { exists = true break } } if !exists { g.imports[pkgPath] = alias return alias } } }
[ "func", "(", "g", "*", "Generator", ")", "pkgAlias", "(", "pkgPath", "string", ")", "string", "{", "pkgPath", "=", "fixPkgPathVendoring", "(", "pkgPath", ")", "\n", "if", "alias", ":=", "g", ".", "imports", "[", "pkgPath", "]", ";", "alias", "!=", "\"\"", "{", "return", "alias", "\n", "}", "\n", "for", "i", ":=", "0", ";", ";", "i", "++", "{", "alias", ":=", "fixAliasName", "(", "path", ".", "Base", "(", "pkgPath", ")", ")", "\n", "if", "i", ">", "0", "{", "alias", "+=", "fmt", ".", "Sprint", "(", "i", ")", "\n", "}", "\n", "exists", ":=", "false", "\n", "for", "_", ",", "v", ":=", "range", "g", ".", "imports", "{", "if", "v", "==", "alias", "{", "exists", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "exists", "{", "g", ".", "imports", "[", "pkgPath", "]", "=", "alias", "\n", "return", "alias", "\n", "}", "\n", "}", "\n", "}" ]
// pkgAlias creates and returns and import alias for a given package.
[ "pkgAlias", "creates", "and", "returns", "and", "import", "alias", "for", "a", "given", "package", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L241-L266
train
mailru/easyjson
gen/generator.go
getType
func (g *Generator) getType(t reflect.Type) string { if t.Name() == "" { switch t.Kind() { case reflect.Ptr: return "*" + g.getType(t.Elem()) case reflect.Slice: return "[]" + g.getType(t.Elem()) case reflect.Array: return "[" + strconv.Itoa(t.Len()) + "]" + g.getType(t.Elem()) case reflect.Map: return "map[" + g.getType(t.Key()) + "]" + g.getType(t.Elem()) } } if t.Name() == "" || t.PkgPath() == "" { if t.Kind() == reflect.Struct { // the fields of an anonymous struct can have named types, // and t.String() will not be sufficient because it does not // remove the package name when it matches g.pkgPath. // so we convert by hand nf := t.NumField() lines := make([]string, 0, nf) for i := 0; i < nf; i++ { f := t.Field(i) var line string if !f.Anonymous { line = f.Name + " " } // else the field is anonymous (an embedded type) line += g.getType(f.Type) t := f.Tag if t != "" { line += " " + escapeTag(t) } lines = append(lines, line) } return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") } return t.String() } else if t.PkgPath() == g.pkgPath { return t.Name() } return g.pkgAlias(t.PkgPath()) + "." + t.Name() }
go
func (g *Generator) getType(t reflect.Type) string { if t.Name() == "" { switch t.Kind() { case reflect.Ptr: return "*" + g.getType(t.Elem()) case reflect.Slice: return "[]" + g.getType(t.Elem()) case reflect.Array: return "[" + strconv.Itoa(t.Len()) + "]" + g.getType(t.Elem()) case reflect.Map: return "map[" + g.getType(t.Key()) + "]" + g.getType(t.Elem()) } } if t.Name() == "" || t.PkgPath() == "" { if t.Kind() == reflect.Struct { // the fields of an anonymous struct can have named types, // and t.String() will not be sufficient because it does not // remove the package name when it matches g.pkgPath. // so we convert by hand nf := t.NumField() lines := make([]string, 0, nf) for i := 0; i < nf; i++ { f := t.Field(i) var line string if !f.Anonymous { line = f.Name + " " } // else the field is anonymous (an embedded type) line += g.getType(f.Type) t := f.Tag if t != "" { line += " " + escapeTag(t) } lines = append(lines, line) } return strings.Join([]string{"struct { ", strings.Join(lines, "; "), " }"}, "") } return t.String() } else if t.PkgPath() == g.pkgPath { return t.Name() } return g.pkgAlias(t.PkgPath()) + "." + t.Name() }
[ "func", "(", "g", "*", "Generator", ")", "getType", "(", "t", "reflect", ".", "Type", ")", "string", "{", "if", "t", ".", "Name", "(", ")", "==", "\"\"", "{", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Ptr", ":", "return", "\"*\"", "+", "g", ".", "getType", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "reflect", ".", "Slice", ":", "return", "\"[]\"", "+", "g", ".", "getType", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "reflect", ".", "Array", ":", "return", "\"[\"", "+", "strconv", ".", "Itoa", "(", "t", ".", "Len", "(", ")", ")", "+", "\"]\"", "+", "g", ".", "getType", "(", "t", ".", "Elem", "(", ")", ")", "\n", "case", "reflect", ".", "Map", ":", "return", "\"map[\"", "+", "g", ".", "getType", "(", "t", ".", "Key", "(", ")", ")", "+", "\"]\"", "+", "g", ".", "getType", "(", "t", ".", "Elem", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "t", ".", "Name", "(", ")", "==", "\"\"", "||", "t", ".", "PkgPath", "(", ")", "==", "\"\"", "{", "if", "t", ".", "Kind", "(", ")", "==", "reflect", ".", "Struct", "{", "nf", ":=", "t", ".", "NumField", "(", ")", "\n", "lines", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "nf", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "nf", ";", "i", "++", "{", "f", ":=", "t", ".", "Field", "(", "i", ")", "\n", "var", "line", "string", "\n", "if", "!", "f", ".", "Anonymous", "{", "line", "=", "f", ".", "Name", "+", "\" \"", "\n", "}", "\n", "line", "+=", "g", ".", "getType", "(", "f", ".", "Type", ")", "\n", "t", ":=", "f", ".", "Tag", "\n", "if", "t", "!=", "\"\"", "{", "line", "+=", "\" \"", "+", "escapeTag", "(", "t", ")", "\n", "}", "\n", "lines", "=", "append", "(", "lines", ",", "line", ")", "\n", "}", "\n", "return", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"struct { \"", ",", "strings", ".", "Join", "(", "lines", ",", "\"; \"", ")", ",", "\" }\"", "}", ",", "\"\"", ")", "\n", "}", "\n", "return", "t", ".", "String", "(", ")", "\n", "}", "else", "if", "t", ".", "PkgPath", "(", ")", "==", "g", ".", "pkgPath", "{", "return", "t", ".", "Name", "(", ")", "\n", "}", "\n", "return", "g", ".", "pkgAlias", "(", "t", ".", "PkgPath", "(", ")", ")", "+", "\".\"", "+", "t", ".", "Name", "(", ")", "\n", "}" ]
// getType return the textual type name of given type that can be used in generated code.
[ "getType", "return", "the", "textual", "type", "name", "of", "given", "type", "that", "can", "be", "used", "in", "generated", "code", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L269-L311
train
mailru/easyjson
gen/generator.go
escapeTag
func escapeTag(tag reflect.StructTag) string { t := string(tag) if strings.ContainsRune(t, '`') { // there are ` in the string; we can't use ` to enclose the string return strconv.Quote(t) } return "`" + t + "`" }
go
func escapeTag(tag reflect.StructTag) string { t := string(tag) if strings.ContainsRune(t, '`') { // there are ` in the string; we can't use ` to enclose the string return strconv.Quote(t) } return "`" + t + "`" }
[ "func", "escapeTag", "(", "tag", "reflect", ".", "StructTag", ")", "string", "{", "t", ":=", "string", "(", "tag", ")", "\n", "if", "strings", ".", "ContainsRune", "(", "t", ",", "'`'", ")", "{", "return", "strconv", ".", "Quote", "(", "t", ")", "\n", "}", "\n", "return", "\"`\"", "+", "t", "+", "\"`\"", "\n", "}" ]
// escape a struct field tag string back to source code
[ "escape", "a", "struct", "field", "tag", "string", "back", "to", "source", "code" ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L314-L321
train
mailru/easyjson
gen/generator.go
uniqueVarName
func (g *Generator) uniqueVarName() string { g.varCounter++ return fmt.Sprint("v", g.varCounter) }
go
func (g *Generator) uniqueVarName() string { g.varCounter++ return fmt.Sprint("v", g.varCounter) }
[ "func", "(", "g", "*", "Generator", ")", "uniqueVarName", "(", ")", "string", "{", "g", ".", "varCounter", "++", "\n", "return", "fmt", ".", "Sprint", "(", "\"v\"", ",", "g", ".", "varCounter", ")", "\n", "}" ]
// uniqueVarName returns a file-unique name that can be used for generated variables.
[ "uniqueVarName", "returns", "a", "file", "-", "unique", "name", "that", "can", "be", "used", "for", "generated", "variables", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L324-L327
train
mailru/easyjson
gen/generator.go
lowerFirst
func lowerFirst(s string) string { if s == "" { return "" } str := "" strlen := len(s) /** Loop each char If is uppercase: If is first char, LOWER it If the following char is lower, LEAVE it If the following char is upper OR numeric, LOWER it If is the end of string, LEAVE it Else lowercase */ foundLower := false for i := range s { ch := s[i] if isUpper(ch) { switch { case i == 0: str += string(ch + 32) case !foundLower: // Currently just a stream of capitals, eg JSONRESTS[erver] if strlen > (i+1) && isLower(s[i+1]) { // Next char is lower, keep this a capital str += string(ch) } else { // Either at end of string or next char is capital str += string(ch + 32) } default: str += string(ch) } } else { foundLower = true str += string(ch) } } return str }
go
func lowerFirst(s string) string { if s == "" { return "" } str := "" strlen := len(s) /** Loop each char If is uppercase: If is first char, LOWER it If the following char is lower, LEAVE it If the following char is upper OR numeric, LOWER it If is the end of string, LEAVE it Else lowercase */ foundLower := false for i := range s { ch := s[i] if isUpper(ch) { switch { case i == 0: str += string(ch + 32) case !foundLower: // Currently just a stream of capitals, eg JSONRESTS[erver] if strlen > (i+1) && isLower(s[i+1]) { // Next char is lower, keep this a capital str += string(ch) } else { // Either at end of string or next char is capital str += string(ch + 32) } default: str += string(ch) } } else { foundLower = true str += string(ch) } } return str }
[ "func", "lowerFirst", "(", "s", "string", ")", "string", "{", "if", "s", "==", "\"\"", "{", "return", "\"\"", "\n", "}", "\n", "str", ":=", "\"\"", "\n", "strlen", ":=", "len", "(", "s", ")", "\n", "foundLower", ":=", "false", "\n", "for", "i", ":=", "range", "s", "{", "ch", ":=", "s", "[", "i", "]", "\n", "if", "isUpper", "(", "ch", ")", "{", "switch", "{", "case", "i", "==", "0", ":", "str", "+=", "string", "(", "ch", "+", "32", ")", "\n", "case", "!", "foundLower", ":", "if", "strlen", ">", "(", "i", "+", "1", ")", "&&", "isLower", "(", "s", "[", "i", "+", "1", "]", ")", "{", "str", "+=", "string", "(", "ch", ")", "\n", "}", "else", "{", "str", "+=", "string", "(", "ch", "+", "32", ")", "\n", "}", "\n", "default", ":", "str", "+=", "string", "(", "ch", ")", "\n", "}", "\n", "}", "else", "{", "foundLower", "=", "true", "\n", "str", "+=", "string", "(", "ch", ")", "\n", "}", "\n", "}", "\n", "return", "str", "\n", "}" ]
// convert HTTPRestClient to httpRestClient
[ "convert", "HTTPRestClient", "to", "httpRestClient" ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/generator.go#L408-L451
train
mailru/easyjson
gen/encoder.go
parseFieldTags
func parseFieldTags(f reflect.StructField) fieldTags { var ret fieldTags for i, s := range strings.Split(f.Tag.Get("json"), ",") { switch { case i == 0 && s == "-": ret.omit = true case i == 0: ret.name = s case s == "omitempty": ret.omitEmpty = true case s == "!omitempty": ret.noOmitEmpty = true case s == "string": ret.asString = true case s == "required": ret.required = true } } return ret }
go
func parseFieldTags(f reflect.StructField) fieldTags { var ret fieldTags for i, s := range strings.Split(f.Tag.Get("json"), ",") { switch { case i == 0 && s == "-": ret.omit = true case i == 0: ret.name = s case s == "omitempty": ret.omitEmpty = true case s == "!omitempty": ret.noOmitEmpty = true case s == "string": ret.asString = true case s == "required": ret.required = true } } return ret }
[ "func", "parseFieldTags", "(", "f", "reflect", ".", "StructField", ")", "fieldTags", "{", "var", "ret", "fieldTags", "\n", "for", "i", ",", "s", ":=", "range", "strings", ".", "Split", "(", "f", ".", "Tag", ".", "Get", "(", "\"json\"", ")", ",", "\",\"", ")", "{", "switch", "{", "case", "i", "==", "0", "&&", "s", "==", "\"-\"", ":", "ret", ".", "omit", "=", "true", "\n", "case", "i", "==", "0", ":", "ret", ".", "name", "=", "s", "\n", "case", "s", "==", "\"omitempty\"", ":", "ret", ".", "omitEmpty", "=", "true", "\n", "case", "s", "==", "\"!omitempty\"", ":", "ret", ".", "noOmitEmpty", "=", "true", "\n", "case", "s", "==", "\"string\"", ":", "ret", ".", "asString", "=", "true", "\n", "case", "s", "==", "\"required\"", ":", "ret", ".", "required", "=", "true", "\n", "}", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// parseFieldTags parses the json field tag into a structure.
[ "parseFieldTags", "parses", "the", "json", "field", "tag", "into", "a", "structure", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/encoder.go#L64-L85
train
mailru/easyjson
gen/encoder.go
genTypeEncoder
func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)") return nil } marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )") return nil } marshalerIface = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.RawText( ("+in+").MarshalText() )") return nil } err := g.genTypeEncoderNoCheck(t, in, tags, indent, assumeNonEmpty) return err }
go
func (g *Generator) genTypeEncoder(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) marshalerIface := reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"("+in+").MarshalEasyJSON(out)") return nil } marshalerIface = reflect.TypeOf((*json.Marshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.Raw( ("+in+").MarshalJSON() )") return nil } marshalerIface = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() if reflect.PtrTo(t).Implements(marshalerIface) { fmt.Fprintln(g.out, ws+"out.RawText( ("+in+").MarshalText() )") return nil } err := g.genTypeEncoderNoCheck(t, in, tags, indent, assumeNonEmpty) return err }
[ "func", "(", "g", "*", "Generator", ")", "genTypeEncoder", "(", "t", "reflect", ".", "Type", ",", "in", "string", ",", "tags", "fieldTags", ",", "indent", "int", ",", "assumeNonEmpty", "bool", ")", "error", "{", "ws", ":=", "strings", ".", "Repeat", "(", "\" \"", ",", "indent", ")", "\n", "marshalerIface", ":=", "reflect", ".", "TypeOf", "(", "(", "*", "easyjson", ".", "Marshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "marshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"(\"", "+", "in", "+", "\").MarshalEasyJSON(out)\"", ")", "\n", "return", "nil", "\n", "}", "\n", "marshalerIface", "=", "reflect", ".", "TypeOf", "(", "(", "*", "json", ".", "Marshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "marshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"out.Raw( (\"", "+", "in", "+", "\").MarshalJSON() )\"", ")", "\n", "return", "nil", "\n", "}", "\n", "marshalerIface", "=", "reflect", ".", "TypeOf", "(", "(", "*", "encoding", ".", "TextMarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", "\n", "if", "reflect", ".", "PtrTo", "(", "t", ")", ".", "Implements", "(", "marshalerIface", ")", "{", "fmt", ".", "Fprintln", "(", "g", ".", "out", ",", "ws", "+", "\"out.RawText( (\"", "+", "in", "+", "\").MarshalText() )\"", ")", "\n", "return", "nil", "\n", "}", "\n", "err", ":=", "g", ".", "genTypeEncoderNoCheck", "(", "t", ",", "in", ",", "tags", ",", "indent", ",", "assumeNonEmpty", ")", "\n", "return", "err", "\n", "}" ]
// genTypeEncoder generates code that encodes in of type t into the writer, but uses marshaler interface if implemented by t.
[ "genTypeEncoder", "generates", "code", "that", "encodes", "in", "of", "type", "t", "into", "the", "writer", "but", "uses", "marshaler", "interface", "if", "implemented", "by", "t", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/encoder.go#L88-L111
train
mailru/easyjson
gen/encoder.go
hasCustomMarshaler
func hasCustomMarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) }
go
func hasCustomMarshaler(t reflect.Type) bool { t = reflect.PtrTo(t) return t.Implements(reflect.TypeOf((*easyjson.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) || t.Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) }
[ "func", "hasCustomMarshaler", "(", "t", "reflect", ".", "Type", ")", "bool", "{", "t", "=", "reflect", ".", "PtrTo", "(", "t", ")", "\n", "return", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "easyjson", ".", "Marshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "||", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "json", ".", "Marshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "||", "t", ".", "Implements", "(", "reflect", ".", "TypeOf", "(", "(", "*", "encoding", ".", "TextMarshaler", ")", "(", "nil", ")", ")", ".", "Elem", "(", ")", ")", "\n", "}" ]
// returns true of the type t implements one of the custom marshaler interfaces
[ "returns", "true", "of", "the", "type", "t", "implements", "one", "of", "the", "custom", "marshaler", "interfaces" ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/encoder.go#L114-L119
train
mailru/easyjson
gen/encoder.go
genTypeEncoderNoCheck
func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) // Check whether type is primitive, needs to be done after interface check. if enc := primitiveStringEncoders[t.Kind()]; enc != "" && tags.asString { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } else if enc := primitiveEncoders[t.Kind()]; enc != "" { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } switch t.Kind() { case reflect.Slice: elem := t.Elem() iVar := g.uniqueVarName() vVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")") } else { if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('[')") fmt.Fprintln(g.out, ws+" for "+iVar+", "+vVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, vVar, tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte(']')") fmt.Fprintln(g.out, ws+"}") } case reflect.Array: elem := t.Elem() iVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+"[:])") } else { fmt.Fprintln(g.out, ws+"out.RawByte('[')") fmt.Fprintln(g.out, ws+"for "+iVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, "("+in+")["+iVar+"]", tags, indent+1, false); err != nil { return err } fmt.Fprintln(g.out, ws+"}") fmt.Fprintln(g.out, ws+"out.RawByte(']')") } case reflect.Struct: enc := g.getEncoderName(t) g.addType(t) fmt.Fprintln(g.out, ws+enc+"(out, "+in+")") case reflect.Ptr: if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } if err := g.genTypeEncoder(t.Elem(), "*"+in, tags, indent+1, false); err != nil { return err } if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"}") } case reflect.Map: key := t.Key() keyEnc, ok := primitiveStringEncoders[key.Kind()] if !ok && !hasCustomMarshaler(key) { return fmt.Errorf("map key type %v not supported: only string and integer keys and types implementing Marshaler interfaces are allowed", key) } // else assume the caller knows what they are doing and that the custom marshaler performs the translation from the key type to a string or integer tmpVar := g.uniqueVarName() if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+" out.RawString(`null`)") fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('{')") fmt.Fprintln(g.out, ws+" "+tmpVar+"First := true") fmt.Fprintln(g.out, ws+" for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+tmpVar+"First { "+tmpVar+"First = false } else { out.RawByte(',') }") // NOTE: extra check for TextMarshaler. It overrides default methods. if reflect.PtrTo(key).Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf("out.RawText(("+tmpVar+"Name).MarshalText()"+")")) } else if keyEnc != "" { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf(keyEnc, tmpVar+"Name")) } else { if err := g.genTypeEncoder(key, tmpVar+"Name", tags, indent+2, false); err != nil { return err } } fmt.Fprintln(g.out, ws+" out.RawByte(':')") if err := g.genTypeEncoder(t.Elem(), tmpVar+"Value", tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte('}')") fmt.Fprintln(g.out, ws+"}") case reflect.Interface: if t.NumMethod() != 0 { return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) } fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") fmt.Fprintln(g.out, ws+"} else if m, ok := "+in+".(json.Marshaler); ok {") fmt.Fprintln(g.out, ws+" out.Raw(m.MarshalJSON())") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" out.Raw(json.Marshal("+in+"))") fmt.Fprintln(g.out, ws+"}") default: return fmt.Errorf("don't know how to encode %v", t) } return nil }
go
func (g *Generator) genTypeEncoderNoCheck(t reflect.Type, in string, tags fieldTags, indent int, assumeNonEmpty bool) error { ws := strings.Repeat(" ", indent) // Check whether type is primitive, needs to be done after interface check. if enc := primitiveStringEncoders[t.Kind()]; enc != "" && tags.asString { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } else if enc := primitiveEncoders[t.Kind()]; enc != "" { fmt.Fprintf(g.out, ws+enc+"\n", in) return nil } switch t.Kind() { case reflect.Slice: elem := t.Elem() iVar := g.uniqueVarName() vVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+")") } else { if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilSliceAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('[')") fmt.Fprintln(g.out, ws+" for "+iVar+", "+vVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, vVar, tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte(']')") fmt.Fprintln(g.out, ws+"}") } case reflect.Array: elem := t.Elem() iVar := g.uniqueVarName() if t.Elem().Kind() == reflect.Uint8 && elem.Name() == "uint8" { fmt.Fprintln(g.out, ws+"out.Base64Bytes("+in+"[:])") } else { fmt.Fprintln(g.out, ws+"out.RawByte('[')") fmt.Fprintln(g.out, ws+"for "+iVar+" := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+iVar+" > 0 {") fmt.Fprintln(g.out, ws+" out.RawByte(',')") fmt.Fprintln(g.out, ws+" }") if err := g.genTypeEncoder(elem, "("+in+")["+iVar+"]", tags, indent+1, false); err != nil { return err } fmt.Fprintln(g.out, ws+"}") fmt.Fprintln(g.out, ws+"out.RawByte(']')") } case reflect.Struct: enc := g.getEncoderName(t) g.addType(t) fmt.Fprintln(g.out, ws+enc+"(out, "+in+")") case reflect.Ptr: if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil {") fmt.Fprintln(g.out, ws+` out.RawString("null")`) fmt.Fprintln(g.out, ws+"} else {") } if err := g.genTypeEncoder(t.Elem(), "*"+in, tags, indent+1, false); err != nil { return err } if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"}") } case reflect.Map: key := t.Key() keyEnc, ok := primitiveStringEncoders[key.Kind()] if !ok && !hasCustomMarshaler(key) { return fmt.Errorf("map key type %v not supported: only string and integer keys and types implementing Marshaler interfaces are allowed", key) } // else assume the caller knows what they are doing and that the custom marshaler performs the translation from the key type to a string or integer tmpVar := g.uniqueVarName() if !assumeNonEmpty { fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {") fmt.Fprintln(g.out, ws+" out.RawString(`null`)") fmt.Fprintln(g.out, ws+"} else {") } else { fmt.Fprintln(g.out, ws+"{") } fmt.Fprintln(g.out, ws+" out.RawByte('{')") fmt.Fprintln(g.out, ws+" "+tmpVar+"First := true") fmt.Fprintln(g.out, ws+" for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {") fmt.Fprintln(g.out, ws+" if "+tmpVar+"First { "+tmpVar+"First = false } else { out.RawByte(',') }") // NOTE: extra check for TextMarshaler. It overrides default methods. if reflect.PtrTo(key).Implements(reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()) { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf("out.RawText(("+tmpVar+"Name).MarshalText()"+")")) } else if keyEnc != "" { fmt.Fprintln(g.out, ws+" "+fmt.Sprintf(keyEnc, tmpVar+"Name")) } else { if err := g.genTypeEncoder(key, tmpVar+"Name", tags, indent+2, false); err != nil { return err } } fmt.Fprintln(g.out, ws+" out.RawByte(':')") if err := g.genTypeEncoder(t.Elem(), tmpVar+"Value", tags, indent+2, false); err != nil { return err } fmt.Fprintln(g.out, ws+" }") fmt.Fprintln(g.out, ws+" out.RawByte('}')") fmt.Fprintln(g.out, ws+"}") case reflect.Interface: if t.NumMethod() != 0 { return fmt.Errorf("interface type %v not supported: only interface{} is allowed", t) } fmt.Fprintln(g.out, ws+"if m, ok := "+in+".(easyjson.Marshaler); ok {") fmt.Fprintln(g.out, ws+" m.MarshalEasyJSON(out)") fmt.Fprintln(g.out, ws+"} else if m, ok := "+in+".(json.Marshaler); ok {") fmt.Fprintln(g.out, ws+" out.Raw(m.MarshalJSON())") fmt.Fprintln(g.out, ws+"} else {") fmt.Fprintln(g.out, ws+" out.Raw(json.Marshal("+in+"))") fmt.Fprintln(g.out, ws+"}") default: return fmt.Errorf("don't know how to encode %v", t) } return nil }
[ "func", "(", "g", "*", "Generator", ")", "genTypeEncoderNoCheck", "(", "t", "reflect", ".", "Type", ",", "in", "string", ",", "tags", "fieldTags", ",", "indent", "int", ",", "assumeNonEmpty", "bool", ")", "error", "{", "ws", ":=", "strings", ".", "Repeat", "(", "\" \"", ",", "indent", ")", "\n", "if", "enc", ":=", "primitiveStringEncoders", "[", "t", ".", "Kind", "(", ")", "]", ";", "enc", "!=", "\"\"", "&&", "tags", ".", "asString", "{", "fmt", ".", "Fprintf", "(", "g", ".", "out", ",", "ws", "+", "enc", "+", "\"\\n\"", ",", "\\n", ")", "\n", "in", "\n", "}", "else", "return", "nil", "\n", "if", "enc", ":=", "primitiveEncoders", "[", "t", ".", "Kind", "(", ")", "]", ";", "enc", "!=", "\"\"", "{", "fmt", ".", "Fprintf", "(", "g", ".", "out", ",", "ws", "+", "enc", "+", "\"\\n\"", ",", "\\n", ")", "\n", "in", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// genTypeEncoderNoCheck generates code that encodes in of type t into the writer.
[ "genTypeEncoderNoCheck", "generates", "code", "that", "encodes", "in", "of", "type", "t", "into", "the", "writer", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/gen/encoder.go#L122-L264
train
mailru/easyjson
bootstrap/bootstrap.go
writeMain
func (g *Generator) writeMain() (path string, err error) { f, err := ioutil.TempFile(filepath.Dir(g.OutName), "easyjson-bootstrap") if err != nil { return "", err } fmt.Fprintln(f, "// +build ignore") fmt.Fprintln(f) fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch") fmt.Fprintln(f, "// the actual generator.") fmt.Fprintln(f) fmt.Fprintln(f, "package main") fmt.Fprintln(f) fmt.Fprintln(f, "import (") fmt.Fprintln(f, ` "fmt"`) fmt.Fprintln(f, ` "os"`) fmt.Fprintln(f) fmt.Fprintf(f, " %q\n", genPackage) if len(g.Types) > 0 { fmt.Fprintln(f) fmt.Fprintf(f, " pkg %q\n", g.PkgPath) } fmt.Fprintln(f, ")") fmt.Fprintln(f) fmt.Fprintln(f, "func main() {") fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName)) fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath) if g.BuildTags != "" { fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags) } if g.SnakeCase { fmt.Fprintln(f, " g.UseSnakeCase()") } if g.LowerCamelCase { fmt.Fprintln(f, " g.UseLowerCamelCase()") } if g.OmitEmpty { fmt.Fprintln(f, " g.OmitEmpty()") } if g.NoStdMarshalers { fmt.Fprintln(f, " g.NoStdMarshalers()") } if g.DisallowUnknownFields { fmt.Fprintln(f, " g.DisallowUnknownFields()") } sort.Strings(g.Types) for _, v := range g.Types { fmt.Fprintln(f, " g.Add(pkg.EasyJSON_exporter_"+v+"(nil))") } fmt.Fprintln(f, " if err := g.Run(os.Stdout); err != nil {") fmt.Fprintln(f, " fmt.Fprintln(os.Stderr, err)") fmt.Fprintln(f, " os.Exit(1)") fmt.Fprintln(f, " }") fmt.Fprintln(f, "}") src := f.Name() if err := f.Close(); err != nil { return src, err } dest := src + ".go" return dest, os.Rename(src, dest) }
go
func (g *Generator) writeMain() (path string, err error) { f, err := ioutil.TempFile(filepath.Dir(g.OutName), "easyjson-bootstrap") if err != nil { return "", err } fmt.Fprintln(f, "// +build ignore") fmt.Fprintln(f) fmt.Fprintln(f, "// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch") fmt.Fprintln(f, "// the actual generator.") fmt.Fprintln(f) fmt.Fprintln(f, "package main") fmt.Fprintln(f) fmt.Fprintln(f, "import (") fmt.Fprintln(f, ` "fmt"`) fmt.Fprintln(f, ` "os"`) fmt.Fprintln(f) fmt.Fprintf(f, " %q\n", genPackage) if len(g.Types) > 0 { fmt.Fprintln(f) fmt.Fprintf(f, " pkg %q\n", g.PkgPath) } fmt.Fprintln(f, ")") fmt.Fprintln(f) fmt.Fprintln(f, "func main() {") fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName)) fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath) if g.BuildTags != "" { fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags) } if g.SnakeCase { fmt.Fprintln(f, " g.UseSnakeCase()") } if g.LowerCamelCase { fmt.Fprintln(f, " g.UseLowerCamelCase()") } if g.OmitEmpty { fmt.Fprintln(f, " g.OmitEmpty()") } if g.NoStdMarshalers { fmt.Fprintln(f, " g.NoStdMarshalers()") } if g.DisallowUnknownFields { fmt.Fprintln(f, " g.DisallowUnknownFields()") } sort.Strings(g.Types) for _, v := range g.Types { fmt.Fprintln(f, " g.Add(pkg.EasyJSON_exporter_"+v+"(nil))") } fmt.Fprintln(f, " if err := g.Run(os.Stdout); err != nil {") fmt.Fprintln(f, " fmt.Fprintln(os.Stderr, err)") fmt.Fprintln(f, " os.Exit(1)") fmt.Fprintln(f, " }") fmt.Fprintln(f, "}") src := f.Name() if err := f.Close(); err != nil { return src, err } dest := src + ".go" return dest, os.Rename(src, dest) }
[ "func", "(", "g", "*", "Generator", ")", "writeMain", "(", ")", "(", "path", "string", ",", "err", "error", ")", "{", "f", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "filepath", ".", "Dir", "(", "g", ".", "OutName", ")", ",", "\"easyjson-bootstrap\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"// +build ignore\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"// TEMPORARY AUTOGENERATED FILE: easyjson bootstapping code to launch\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"// the actual generator.\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"package main\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"import (\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "` \"fmt\"`", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "` \"os\"`", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintf", "(", "f", ",", "\" %q\\n\"", ",", "\\n", ")", "\n", "genPackage", "\n", "if", "len", "(", "g", ".", "Types", ")", ">", "0", "{", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintf", "(", "f", ",", "\" pkg %q\\n\"", ",", "\\n", ")", "\n", "}", "\n", "g", ".", "PkgPath", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\")\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\"func main() {\"", ")", "\n", "fmt", ".", "Fprintf", "(", "f", ",", "\" g := gen.NewGenerator(%q)\\n\"", ",", "\\n", ")", "\n", "filepath", ".", "Base", "(", "g", ".", "OutName", ")", "\n", "fmt", ".", "Fprintf", "(", "f", ",", "\" g.SetPkg(%q, %q)\\n\"", ",", "\\n", ",", "g", ".", "PkgName", ")", "\n", "g", ".", "PkgPath", "\n", "if", "g", ".", "BuildTags", "!=", "\"\"", "{", "fmt", ".", "Fprintf", "(", "f", ",", "\" g.SetBuildTags(%q)\\n\"", ",", "\\n", ")", "\n", "}", "\n", "g", ".", "BuildTags", "\n", "if", "g", ".", "SnakeCase", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.UseSnakeCase()\"", ")", "\n", "}", "\n", "if", "g", ".", "LowerCamelCase", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.UseLowerCamelCase()\"", ")", "\n", "}", "\n", "if", "g", ".", "OmitEmpty", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.OmitEmpty()\"", ")", "\n", "}", "\n", "if", "g", ".", "NoStdMarshalers", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.NoStdMarshalers()\"", ")", "\n", "}", "\n", "if", "g", ".", "DisallowUnknownFields", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.DisallowUnknownFields()\"", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "g", ".", "Types", ")", "\n", "for", "_", ",", "v", ":=", "range", "g", ".", "Types", "{", "fmt", ".", "Fprintln", "(", "f", ",", "\" g.Add(pkg.EasyJSON_exporter_\"", "+", "v", "+", "\"(nil))\"", ")", "\n", "}", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\" if err := g.Run(os.Stdout); err != nil {\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\" fmt.Fprintln(os.Stderr, err)\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\" os.Exit(1)\"", ")", "\n", "fmt", ".", "Fprintln", "(", "f", ",", "\" }\"", ")", "\n", "}" ]
// writeMain creates a .go file that launches the generator if 'go run'.
[ "writeMain", "creates", "a", ".", "go", "file", "that", "launches", "the", "generator", "if", "go", "run", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/bootstrap/bootstrap.go#L82-L146
train
mailru/easyjson
jwriter/writer.go
DumpTo
func (w *Writer) DumpTo(out io.Writer) (written int, err error) { return w.Buffer.DumpTo(out) }
go
func (w *Writer) DumpTo(out io.Writer) (written int, err error) { return w.Buffer.DumpTo(out) }
[ "func", "(", "w", "*", "Writer", ")", "DumpTo", "(", "out", "io", ".", "Writer", ")", "(", "written", "int", ",", "err", "error", ")", "{", "return", "w", ".", "Buffer", ".", "DumpTo", "(", "out", ")", "\n", "}" ]
// DumpTo outputs the data to given io.Writer, resetting the buffer.
[ "DumpTo", "outputs", "the", "data", "to", "given", "io", ".", "Writer", "resetting", "the", "buffer", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/jwriter/writer.go#L36-L38
train
mailru/easyjson
jwriter/writer.go
BuildBytes
func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.BuildBytes(reuse...), nil }
go
func (w *Writer) BuildBytes(reuse ...[]byte) ([]byte, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.BuildBytes(reuse...), nil }
[ "func", "(", "w", "*", "Writer", ")", "BuildBytes", "(", "reuse", "...", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "if", "w", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "w", ".", "Error", "\n", "}", "\n", "return", "w", ".", "Buffer", ".", "BuildBytes", "(", "reuse", "...", ")", ",", "nil", "\n", "}" ]
// BuildBytes returns writer data as a single byte slice. You can optionally provide one byte slice // as argument that it will try to reuse.
[ "BuildBytes", "returns", "writer", "data", "as", "a", "single", "byte", "slice", ".", "You", "can", "optionally", "provide", "one", "byte", "slice", "as", "argument", "that", "it", "will", "try", "to", "reuse", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/jwriter/writer.go#L42-L48
train
mailru/easyjson
jwriter/writer.go
ReadCloser
func (w *Writer) ReadCloser() (io.ReadCloser, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.ReadCloser(), nil }
go
func (w *Writer) ReadCloser() (io.ReadCloser, error) { if w.Error != nil { return nil, w.Error } return w.Buffer.ReadCloser(), nil }
[ "func", "(", "w", "*", "Writer", ")", "ReadCloser", "(", ")", "(", "io", ".", "ReadCloser", ",", "error", ")", "{", "if", "w", ".", "Error", "!=", "nil", "{", "return", "nil", ",", "w", ".", "Error", "\n", "}", "\n", "return", "w", ".", "Buffer", ".", "ReadCloser", "(", ")", ",", "nil", "\n", "}" ]
// ReadCloser returns an io.ReadCloser that can be used to read the data. // ReadCloser also resets the buffer.
[ "ReadCloser", "returns", "an", "io", ".", "ReadCloser", "that", "can", "be", "used", "to", "read", "the", "data", ".", "ReadCloser", "also", "resets", "the", "buffer", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/jwriter/writer.go#L52-L58
train
mailru/easyjson
jwriter/writer.go
Raw
func (w *Writer) Raw(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.Buffer.AppendBytes(data) default: w.RawString("null") } }
go
func (w *Writer) Raw(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.Buffer.AppendBytes(data) default: w.RawString("null") } }
[ "func", "(", "w", "*", "Writer", ")", "Raw", "(", "data", "[", "]", "byte", ",", "err", "error", ")", "{", "switch", "{", "case", "w", ".", "Error", "!=", "nil", ":", "return", "\n", "case", "err", "!=", "nil", ":", "w", ".", "Error", "=", "err", "\n", "case", "len", "(", "data", ")", ">", "0", ":", "w", ".", "Buffer", ".", "AppendBytes", "(", "data", ")", "\n", "default", ":", "w", ".", "RawString", "(", "\"null\"", ")", "\n", "}", "\n", "}" ]
// Raw appends raw binary data to the buffer or sets the error if it is given. Useful for // calling with results of MarshalJSON-like functions.
[ "Raw", "appends", "raw", "binary", "data", "to", "the", "buffer", "or", "sets", "the", "error", "if", "it", "is", "given", ".", "Useful", "for", "calling", "with", "results", "of", "MarshalJSON", "-", "like", "functions", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/jwriter/writer.go#L72-L83
train
mailru/easyjson
jwriter/writer.go
RawText
func (w *Writer) RawText(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.String(string(data)) default: w.RawString("null") } }
go
func (w *Writer) RawText(data []byte, err error) { switch { case w.Error != nil: return case err != nil: w.Error = err case len(data) > 0: w.String(string(data)) default: w.RawString("null") } }
[ "func", "(", "w", "*", "Writer", ")", "RawText", "(", "data", "[", "]", "byte", ",", "err", "error", ")", "{", "switch", "{", "case", "w", ".", "Error", "!=", "nil", ":", "return", "\n", "case", "err", "!=", "nil", ":", "w", ".", "Error", "=", "err", "\n", "case", "len", "(", "data", ")", ">", "0", ":", "w", ".", "String", "(", "string", "(", "data", ")", ")", "\n", "default", ":", "w", ".", "RawString", "(", "\"null\"", ")", "\n", "}", "\n", "}" ]
// RawText encloses raw binary data in quotes and appends in to the buffer. // Useful for calling with results of MarshalText-like functions.
[ "RawText", "encloses", "raw", "binary", "data", "in", "quotes", "and", "appends", "in", "to", "the", "buffer", ".", "Useful", "for", "calling", "with", "results", "of", "MarshalText", "-", "like", "functions", "." ]
1ea4449da9834f4d333f1cc461c374aea217d249
https://github.com/mailru/easyjson/blob/1ea4449da9834f4d333f1cc461c374aea217d249/jwriter/writer.go#L87-L98
train