<commit_before>package errors

import (
	"fmt"
	"net/url"

	"github.com/pkg/errors"
)

// IsFatalError indicates that the error is fatal and the process should exit
// immediately after handling the error.
func IsFatalError(err error) bool {
	if e, ok := err.(interface {
		Fatal() bool
	}); ok {
		return e.Fatal()
	}
	if parent := parentOf(err); parent != nil {
		return IsFatalError(parent)
	}
	return false
}

// IsNotImplementedError indicates the client attempted to use a feature the
// server has not implemented (e.g. the batch endpoint).
func IsNotImplementedError(err error) bool {
	if e, ok := err.(interface {
		NotImplemented() bool
	}); ok {
		return e.NotImplemented()
	}
	if parent := parentOf(err); parent != nil {
		return IsNotImplementedError(parent)
	}
	return false
}

// IsAuthError indicates the client provided a request with invalid or no
// authentication credentials when credentials are required (e.g. HTTP 401).
func IsAuthError(err error) bool {
	if e, ok := err.(interface {
		AuthError() bool
	}); ok {
		return e.AuthError()
	}
	if parent := parentOf(err); parent != nil {
		return IsAuthError(parent)
	}
	return false
}

// IsSmudgeError indicates an error while smudging a files.
func IsSmudgeError(err error) bool {
	if e, ok := err.(interface {
		SmudgeError() bool
	}); ok {
		return e.SmudgeError()
	}
	if parent := parentOf(err); parent != nil {
		return IsSmudgeError(parent)
	}
	return false
}

// IsCleanPointerError indicates an error while cleaning a file.
func IsCleanPointerError(err error) bool {
	if e, ok := err.(interface {
		CleanPointerError() bool
	}); ok {
		return e.CleanPointerError()
	}
	if parent := parentOf(err); parent != nil {
		return IsCleanPointerError(parent)
	}
	return false
}

// IsNotAPointerError indicates the parsed data is not an LFS pointer.
func IsNotAPointerError(err error) bool {
	if e, ok := err.(interface {
		NotAPointerError() bool
	}); ok {
		return e.NotAPointerError()
	}
	if parent := parentOf(err); parent != nil {
		return IsNotAPointerError(parent)
	}
	return false
}

// IsBadPointerKeyError indicates that the parsed data has an invalid key.
func IsBadPointerKeyError(err error) bool {
	if e, ok := err.(interface {
		BadPointerKeyError() bool
	}); ok {
		return e.BadPointerKeyError()
	}

	if parent := parentOf(err); parent != nil {
		return IsBadPointerKeyError(parent)
	}
	return false
}

// If an error is abad pointer error of any type, returns NotAPointerError
func StandardizeBadPointerError(err error) error {
	if IsBadPointerKeyError(err) {
		badErr := err.(badPointerKeyError)
		if badErr.Expected == "version" {
			return NewNotAPointerError(err)
		}
	}
	return err
}

// IsDownloadDeclinedError indicates that the smudge operation should not download.
// TODO: I don't really like using errors to control that flow, it should be refactored.
func IsDownloadDeclinedError(err error) bool {
	if e, ok := err.(interface {
		DownloadDeclinedError() bool
	}); ok {
		return e.DownloadDeclinedError()
	}
	if parent := parentOf(err); parent != nil {
		return IsDownloadDeclinedError(parent)
	}
	return false
}

// IsRetriableError indicates the low level transfer had an error but the
// caller may retry the operation.
func IsRetriableError(err error) bool {
	if e, ok := err.(interface {
		RetriableError() bool
	}); ok {
		return e.RetriableError()
	}
	if cause, ok := Cause(err).(*url.Error); ok {
		return cause.Temporary() || cause.Timeout()
	}
	if parent := parentOf(err); parent != nil {
		return IsRetriableError(parent)
	}
	return false
}

type errorWithCause interface {
	Cause() error
	StackTrace() errors.StackTrace
	error
	fmt.Formatter
}

// wrappedError is the base error wrapper. It provides a Message string, a
// stack, and a context map around a regular Go error.
type wrappedError struct {
	errorWithCause
	context map[string]interface{}
}

// newWrappedError creates a wrappedError.
func newWrappedError(err error, message string) *wrappedError {
	if err == nil {
		err = errors.New("Error")
	}

	var errWithCause errorWithCause

	if len(message) > 0 {
		errWithCause = errors.Wrap(err, message).(errorWithCause)
	} else if ewc, ok := err.(errorWithCause); ok {
		errWithCause = ewc
	} else {
		errWithCause = errors.Wrap(err, "LFS").(errorWithCause)
	}

	return &wrappedError{
		context:        make(map[string]interface{}),
		errorWithCause: errWithCause,
	}
}

// Set sets the value for the key in the context.
func (e wrappedError) Set(key string, val interface{}) {
	e.context[key] = val
}

// Get gets the value for a key in the context.
func (e wrappedError) Get(key string) interface{} {
	return e.context[key]
}

// Del removes a key from the context.
func (e wrappedError) Del(key string) {
	delete(e.context, key)
}

// Context returns the underlying context.
func (e wrappedError) Context() map[string]interface{} {
	return e.context
}

// Definitions for IsFatalError()

type fatalError struct {
	*wrappedError
}

func (e fatalError) Fatal() bool {
	return true
}

func NewFatalError(err error) error {
	return fatalError{newWrappedError(err, "Fatal error")}
}

// Definitions for IsNotImplementedError()

type notImplementedError struct {
	*wrappedError
}

func (e notImplementedError) NotImplemented() bool {
	return true
}

func NewNotImplementedError(err error) error {
	return notImplementedError{newWrappedError(err, "Not implemented")}
}

// Definitions for IsAuthError()

type authError struct {
	*wrappedError
}

func (e authError) AuthError() bool {
	return true
}

func NewAuthError(err error) error {
	return authError{newWrappedError(err, "Authentication required")}
}

// Definitions for IsSmudgeError()

type smudgeError struct {
	*wrappedError
}

func (e smudgeError) SmudgeError() bool {
	return true
}

func NewSmudgeError(err error, oid, filename string) error {
	e := smudgeError{newWrappedError(err, "Smudge error")}
	SetContext(e, "OID", oid)
	SetContext(e, "FileName", filename)
	return e
}

// Definitions for IsCleanPointerError()

type cleanPointerError struct {
	*wrappedError
}

func (e cleanPointerError) CleanPointerError() bool {
	return true
}

func NewCleanPointerError(pointer interface{}, bytes []byte) error {
	err := New("pointer error")
	e := cleanPointerError{newWrappedError(err, "clean")}
	SetContext(e, "pointer", pointer)
	SetContext(e, "bytes", bytes)
	return e
}

// Definitions for IsNotAPointerError()

type notAPointerError struct {
	*wrappedError
}

func (e notAPointerError) NotAPointerError() bool {
	return true
}

func NewNotAPointerError(err error) error {
	return notAPointerError{newWrappedError(err, "Pointer file error")}
}

type badPointerKeyError struct {
	Expected string
	Actual   string

	*wrappedError
}

func (e badPointerKeyError) BadPointerKeyError() bool {
	return true
}

func NewBadPointerKeyError(expected, actual string) error {
	err := Errorf("Expected key %s, got %s", expected, actual)
	return badPointerKeyError{expected, actual, newWrappedError(err, "pointer parsing")}
}

// Definitions for IsDownloadDeclinedError()

type downloadDeclinedError struct {
	*wrappedError
}

func (e downloadDeclinedError) DownloadDeclinedError() bool {
	return true
}

func NewDownloadDeclinedError(err error, msg string) error {
	return downloadDeclinedError{newWrappedError(err, msg)}
}

// Definitions for IsRetriableError()

type retriableError struct {
	*wrappedError
}

func (e retriableError) RetriableError() bool {
	return true
}

func NewRetriableError(err error) error {
	return retriableError{newWrappedError(err, "")}
}

func parentOf(err error) error {
	type causer interface {
		Cause() error
	}

	if c, ok := err.(causer); ok {
		if innerC, innerOk := c.Cause().(causer); innerOk {
			return innerC.Cause()
		}
	}

	return nil
}
<commit_msg>errors/types.go: add a new UnprocessableEntityError<commit_after>package errors

import (
	"fmt"
	"net/url"

	"github.com/pkg/errors"
)

// IsFatalError indicates that the error is fatal and the process should exit
// immediately after handling the error.
func IsFatalError(err error) bool {
	if e, ok := err.(interface {
		Fatal() bool
	}); ok {
		return e.Fatal()
	}
	if parent := parentOf(err); parent != nil {
		return IsFatalError(parent)
	}
	return false
}

// IsNotImplementedError indicates the client attempted to use a feature the
// server has not implemented (e.g. the batch endpoint).
func IsNotImplementedError(err error) bool {
	if e, ok := err.(interface {
		NotImplemented() bool
	}); ok {
		return e.NotImplemented()
	}
	if parent := parentOf(err); parent != nil {
		return IsNotImplementedError(parent)
	}
	return false
}

// IsAuthError indicates the client provided a request with invalid or no
// authentication credentials when credentials are required (e.g. HTTP 401).
func IsAuthError(err error) bool {
	if e, ok := err.(interface {
		AuthError() bool
	}); ok {
		return e.AuthError()
	}
	if parent := parentOf(err); parent != nil {
		return IsAuthError(parent)
	}
	return false
}

// IsSmudgeError indicates an error while smudging a files.
func IsSmudgeError(err error) bool {
	if e, ok := err.(interface {
		SmudgeError() bool
	}); ok {
		return e.SmudgeError()
	}
	if parent := parentOf(err); parent != nil {
		return IsSmudgeError(parent)
	}
	return false
}

// IsCleanPointerError indicates an error while cleaning a file.
func IsCleanPointerError(err error) bool {
	if e, ok := err.(interface {
		CleanPointerError() bool
	}); ok {
		return e.CleanPointerError()
	}
	if parent := parentOf(err); parent != nil {
		return IsCleanPointerError(parent)
	}
	return false
}

// IsNotAPointerError indicates the parsed data is not an LFS pointer.
func IsNotAPointerError(err error) bool {
	if e, ok := err.(interface {
		NotAPointerError() bool
	}); ok {
		return e.NotAPointerError()
	}
	if parent := parentOf(err); parent != nil {
		return IsNotAPointerError(parent)
	}
	return false
}

// IsBadPointerKeyError indicates that the parsed data has an invalid key.
func IsBadPointerKeyError(err error) bool {
	if e, ok := err.(interface {
		BadPointerKeyError() bool
	}); ok {
		return e.BadPointerKeyError()
	}

	if parent := parentOf(err); parent != nil {
		return IsBadPointerKeyError(parent)
	}
	return false
}

// If an error is abad pointer error of any type, returns NotAPointerError
func StandardizeBadPointerError(err error) error {
	if IsBadPointerKeyError(err) {
		badErr := err.(badPointerKeyError)
		if badErr.Expected == "version" {
			return NewNotAPointerError(err)
		}
	}
	return err
}

// IsDownloadDeclinedError indicates that the smudge operation should not download.
// TODO: I don't really like using errors to control that flow, it should be refactored.
func IsDownloadDeclinedError(err error) bool {
	if e, ok := err.(interface {
		DownloadDeclinedError() bool
	}); ok {
		return e.DownloadDeclinedError()
	}
	if parent := parentOf(err); parent != nil {
		return IsDownloadDeclinedError(parent)
	}
	return false
}

// IsDownloadDeclinedError indicates that the upload operation failed because of
// an HTTP 422 response code.
func IsUnprocessableEntityError(err error) bool {
	if e, ok := err.(interface {
		UnprocessableEntityError() bool
	}); ok {
		return e.UnprocessableEntityError()
	}
	if parent := parentOf(err); parent != nil {
		return IsUnprocessableEntityError(parent)
	}
	return false
}

// IsRetriableError indicates the low level transfer had an error but the
// caller may retry the operation.
func IsRetriableError(err error) bool {
	if e, ok := err.(interface {
		RetriableError() bool
	}); ok {
		return e.RetriableError()
	}
	if cause, ok := Cause(err).(*url.Error); ok {
		return cause.Temporary() || cause.Timeout()
	}
	if parent := parentOf(err); parent != nil {
		return IsRetriableError(parent)
	}
	return false
}

type errorWithCause interface {
	Cause() error
	StackTrace() errors.StackTrace
	error
	fmt.Formatter
}

// wrappedError is the base error wrapper. It provides a Message string, a
// stack, and a context map around a regular Go error.
type wrappedError struct {
	errorWithCause
	context map[string]interface{}
}

// newWrappedError creates a wrappedError.
func newWrappedError(err error, message string) *wrappedError {
	if err == nil {
		err = errors.New("Error")
	}

	var errWithCause errorWithCause

	if len(message) > 0 {
		errWithCause = errors.Wrap(err, message).(errorWithCause)
	} else if ewc, ok := err.(errorWithCause); ok {
		errWithCause = ewc
	} else {
		errWithCause = errors.Wrap(err, "LFS").(errorWithCause)
	}

	return &wrappedError{
		context:        make(map[string]interface{}),
		errorWithCause: errWithCause,
	}
}

// Set sets the value for the key in the context.
func (e wrappedError) Set(key string, val interface{}) {
	e.context[key] = val
}

// Get gets the value for a key in the context.
func (e wrappedError) Get(key string) interface{} {
	return e.context[key]
}

// Del removes a key from the context.
func (e wrappedError) Del(key string) {
	delete(e.context, key)
}

// Context returns the underlying context.
func (e wrappedError) Context() map[string]interface{} {
	return e.context
}

// Definitions for IsFatalError()

type fatalError struct {
	*wrappedError
}

func (e fatalError) Fatal() bool {
	return true
}

func NewFatalError(err error) error {
	return fatalError{newWrappedError(err, "Fatal error")}
}

// Definitions for IsNotImplementedError()

type notImplementedError struct {
	*wrappedError
}

func (e notImplementedError) NotImplemented() bool {
	return true
}

func NewNotImplementedError(err error) error {
	return notImplementedError{newWrappedError(err, "Not implemented")}
}

// Definitions for IsAuthError()

type authError struct {
	*wrappedError
}

func (e authError) AuthError() bool {
	return true
}

func NewAuthError(err error) error {
	return authError{newWrappedError(err, "Authentication required")}
}

// Definitions for IsSmudgeError()

type smudgeError struct {
	*wrappedError
}

func (e smudgeError) SmudgeError() bool {
	return true
}

func NewSmudgeError(err error, oid, filename string) error {
	e := smudgeError{newWrappedError(err, "Smudge error")}
	SetContext(e, "OID", oid)
	SetContext(e, "FileName", filename)
	return e
}

// Definitions for IsCleanPointerError()

type cleanPointerError struct {
	*wrappedError
}

func (e cleanPointerError) CleanPointerError() bool {
	return true
}

func NewCleanPointerError(pointer interface{}, bytes []byte) error {
	err := New("pointer error")
	e := cleanPointerError{newWrappedError(err, "clean")}
	SetContext(e, "pointer", pointer)
	SetContext(e, "bytes", bytes)
	return e
}

// Definitions for IsNotAPointerError()

type notAPointerError struct {
	*wrappedError
}

func (e notAPointerError) NotAPointerError() bool {
	return true
}

func NewNotAPointerError(err error) error {
	return notAPointerError{newWrappedError(err, "Pointer file error")}
}

type badPointerKeyError struct {
	Expected string
	Actual   string

	*wrappedError
}

func (e badPointerKeyError) BadPointerKeyError() bool {
	return true
}

func NewBadPointerKeyError(expected, actual string) error {
	err := Errorf("Expected key %s, got %s", expected, actual)
	return badPointerKeyError{expected, actual, newWrappedError(err, "pointer parsing")}
}

// Definitions for IsDownloadDeclinedError()

type downloadDeclinedError struct {
	*wrappedError
}

func (e downloadDeclinedError) DownloadDeclinedError() bool {
	return true
}

func NewDownloadDeclinedError(err error, msg string) error {
	return downloadDeclinedError{newWrappedError(err, msg)}
}

// Definitions for IsUnprocessableEntityError()

type unprocessableEntityError struct {
	*wrappedError
}

func (e unprocessableEntityError) UnprocessableEntityError() bool {
	return true
}

func NewUnprocessableEntityError(err error) error {
	return unprocessableEntityError{newWrappedError(err, "")}
}

// Definitions for IsRetriableError()

type retriableError struct {
	*wrappedError
}

func (e retriableError) RetriableError() bool {
	return true
}

func NewRetriableError(err error) error {
	return retriableError{newWrappedError(err, "")}
}

func parentOf(err error) error {
	type causer interface {
		Cause() error
	}

	if c, ok := err.(causer); ok {
		if innerC, innerOk := c.Cause().(causer); innerOk {
			return innerC.Cause()
		}
	}

	return nil
}
<|endoftext|>


<commit_before>package dragon

import "fmt"

func out(libChan chan lib, done chan struct{}) {
	for lib := range libChan {
		fmt.Printf("%s.%s: %s\n", lib.pkg, lib.object, lib.path)
	}
	done <- struct{}{}
}
<commit_msg>Implemented out to goimports's zstdlib.go<commit_after>package dragon

import (
	"bytes"
	"fmt"
	"go/format"
	"log"
	"os"
	"path/filepath"
	"sort"
)

func out(libChan chan lib, done chan struct{}) {
	libs := map[string]lib{}
	ambiguous := map[string]bool{}
	var keys []string

	for lib := range libChan {
		full := lib.path
		key := lib.pkg + "." + lib.object
		if exist, ok := libs[key]; ok {
			if exist.path != full {
				ambiguous[key] = true
			}
		} else {
			libs[key] = lib
			keys = append(keys, key)
		}
	}
	sort.Strings(keys)

	var buf bytes.Buffer
	outf := func(format string, args ...interface{}) {
		fmt.Fprintf(&buf, format, args...)
	}
	outf("// AUTO-GENERATED BY dragon-imports\n\n")
	outf("package imports\n")
	outf("var stdlib = map[string]string{\n")

	for _, key := range keys {
		if ambiguous[key] {
			outf("\t// %q is ambiguous\n", key)
		} else {
			outf("\t%q: %q,\n", key, libs[key].path)
		}
	}
	outf("}\n")
	fmtbuf, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	f, err := os.OpenFile(filepath.Join(outPath(), "zstdlib.go"), os.O_WRONLY, 0644)
	if err != nil {
		log.Fatal(err)
	}
	f.Write(fmtbuf)
	f.Close()
	done <- struct{}{}
}

func outPath() string {
	for _, src := range srcDirs() {
		outPath := filepath.Join(src, "golang.org/x/tools/imports")
		if _, err := os.Stat(outPath); err == nil {
			return outPath
		}
	}
	return ""
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"golang.org/x/crypto/sha3"
	//"bytes"
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"github.com/gorilla/mux"
	//"golang.org/x/crypto/sha3"
	"gopkg.in/redis.v3"
	"html/template"
	"io"
	//"encoding/base64"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

/*
//=====================================
// general strategy:
// we take in a file, the filename is a hashed random string.
// the file is stored with its filename as the hased string.
// the random string (token) is returned back to the user.
//
// now when the user wants to retrive the file, he puts in the
// token (random string from earlier). his request is hashed and
// the stored has is returned. ez
//=====================================
*/

func main() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", landingpage).Methods("GET")
	router.HandleFunc("/css/style.css", css).Methods("GET")
	router.HandleFunc("/js/index.js", js).Methods("GET")
	router.HandleFunc("/bitnuke.png", img).Methods("GET")
	router.HandleFunc("/{fdata}", handlerdynamic).Methods("GET")
	router.HandleFunc("/upload", upload)
	log.Fatal(http.ListenAndServe(":8802", router))
}

func landingpage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/index.html")
}

func css(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/css/style.css")
}

func js(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/js/index.js")
}

func img(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/bitnuke.png")
}

func handlerdynamic(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	fdata := vars["fdata"]
	// init redis client
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	// hash the token that is passed
	hash := sha3.Sum512([]byte(fdata))
	hashstr := fmt.Sprintf("%x", hash)

	val, err := client.Get(hashstr).Result()
	if err != nil {
		log.Printf("data does not exist")
		fmt.Fprintf(w, "token not found")
	} else {
		log.Printf("data exists")
		log.Printf("Responsing to %x", hashstr)

		decodeVal, _ := base64.StdEncoding.DecodeString(val)

		file, _ := os.Create("tmpfile")
		io.WriteString(file, string(decodeVal))
		file.Close()

		http.ServeFile(w, r, "tmpfile")
		os.Remove("tmpfile")
	}
}

func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, _, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		//fmt.Fprintf(w, "%v", handler.Header)

		// generate token and hash to save
		token := randStr(8)
		fmt.Fprintf(w, ""+
			""+
			"
https://bitnuke.io/%v
"+
			"", token, token)
		hash := sha3.Sum512([]byte(token))
		hashstr := fmt.Sprintf("%x", hash)
		fmt.Println(token)

		// write file temporarily to get filesize
		f, _ := os.OpenFile("tmpfile", os.O_WRONLY|os.O_CREATE, 0666)
		defer f.Close()
		io.Copy(f, file)

		tmpFile, _ := os.Open("tmpfile")
		defer tmpFile.Close()

		client := redis.NewClient(&redis.Options{
			Addr:     "localhost:6379",
			Password: "",
			DB:       0,
		})

		fInfo, _ := tmpFile.Stat()
		var size int64 = fInfo.Size()
		buf := make([]byte, size)

		// read file content into buffer
		fReader := bufio.NewReader(tmpFile)
		fReader.Read(buf)

		fileBase64Str := base64.StdEncoding.EncodeToString(buf)

		println("uploading ", "file")
		client.Set(hashstr, fileBase64Str, 0).Err()
		os.Remove("tmpfile")
	}
}

func tokenserv(w http.ResponseWriter, r *http.Request, data string) {
	log.Printf("Responsing to", data)
	item := fmt.Sprintf("./tmpnuke/%s", data)
	http.ServeFile(w, r, item)
}

func randStr(strSize int) string {
	dictionary := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

	var bytes = make([]byte, strSize)
	rand.Read(bytes)
	for k, v := range bytes {
		bytes[k] = dictionary[v%byte(len(dictionary))]
	}
	return string(bytes)
}
<commit_msg>24 hour timeout<commit_after>package main

import (
	"bufio"
	"golang.org/x/crypto/sha3"
	//"bytes"
	"crypto/md5"
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"github.com/gorilla/mux"
	//"golang.org/x/crypto/sha3"
	"gopkg.in/redis.v3"
	"html/template"
	"io"
	//"encoding/base64"
	"log"
	"net/http"
	"os"
	"strconv"
	"time"
)

/*
//=====================================
// general strategy:
// we take in a file, the filename is a hashed random string.
// the file is stored with its filename as the hased string.
// the random string (token) is returned back to the user.
//
// now when the user wants to retrive the file, he puts in the
// token (random string from earlier). his request is hashed and
// the stored has is returned. ez
//=====================================
*/

func main() {
	router := mux.NewRouter().StrictSlash(true)
	router.HandleFunc("/", landingpage).Methods("GET")
	router.HandleFunc("/css/style.css", css).Methods("GET")
	router.HandleFunc("/js/index.js", js).Methods("GET")
	router.HandleFunc("/bitnuke.png", img).Methods("GET")
	router.HandleFunc("/{fdata}", handlerdynamic).Methods("GET")
	router.HandleFunc("/upload", upload)
	log.Fatal(http.ListenAndServe(":8802", router))
}

func landingpage(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/index.html")
}

func css(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/css/style.css")
}

func js(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/js/index.js")
}

func img(w http.ResponseWriter, r *http.Request) {
	//w.Header().Set("Content-Type", "text/html")
	http.ServeFile(w, r, "./upload/bitnuke.png")
}

func handlerdynamic(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	fdata := vars["fdata"]
	// init redis client
	client := redis.NewClient(&redis.Options{
		Addr:     "localhost:6379",
		Password: "",
		DB:       0,
	})

	// hash the token that is passed
	hash := sha3.Sum512([]byte(fdata))
	hashstr := fmt.Sprintf("%x", hash)

	val, err := client.Get(hashstr).Result()
	if err != nil {
		log.Printf("data does not exist")
		fmt.Fprintf(w, "token not found")
	} else {
		log.Printf("data exists")
		log.Printf("Responsing to %x", hashstr)

		decodeVal, _ := base64.StdEncoding.DecodeString(val)

		file, _ := os.Create("tmpfile")
		io.WriteString(file, string(decodeVal))
		file.Close()

		http.ServeFile(w, r, "tmpfile")
		os.Remove("tmpfile")
	}
}

func upload(w http.ResponseWriter, r *http.Request) {
	fmt.Println("method:", r.Method)
	if r.Method == "GET" {
		crutime := time.Now().Unix()
		h := md5.New()
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		token := fmt.Sprintf("%x", h.Sum(nil))

		t, _ := template.ParseFiles("upload.gtpl")
		t.Execute(w, token)
	} else {
		r.ParseMultipartForm(32 << 20)
		file, _, err := r.FormFile("uploadfile")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		//fmt.Fprintf(w, "%v", handler.Header)

		// generate token and hash to save
		token := randStr(8)
		fmt.Fprintf(w, ""+
			""+
			"
https://bitnuke.io/%v
"+
			"", token, token)
		hash := sha3.Sum512([]byte(token))
		hashstr := fmt.Sprintf("%x", hash)
		fmt.Println(token)

		// write file temporarily to get filesize
		f, _ := os.OpenFile("tmpfile", os.O_WRONLY|os.O_CREATE, 0666)
		defer f.Close()
		io.Copy(f, file)

		tmpFile, _ := os.Open("tmpfile")
		defer tmpFile.Close()

		client := redis.NewClient(&redis.Options{
			Addr:     "localhost:6379",
			Password: "",
			DB:       0,
		})

		fInfo, _ := tmpFile.Stat()
		var size int64 = fInfo.Size()
		buf := make([]byte, size)

		// read file content into buffer
		fReader := bufio.NewReader(tmpFile)
		fReader.Read(buf)

		fileBase64Str := base64.StdEncoding.EncodeToString(buf)

		println("uploading ", "file")
		client.Set(hashstr, fileBase64Str, 0).Err()
		client.Expire(hashstr, (24 * time.Hour)).Err()
		os.Remove("tmpfile")
	}
}

func tokenserv(w http.ResponseWriter, r *http.Request, data string) {
	log.Printf("Responsing to", data)
	item := fmt.Sprintf("./tmpnuke/%s", data)
	http.ServeFile(w, r, item)
}

func randStr(strSize int) string {
	dictionary := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"

	var bytes = make([]byte, strSize)
	rand.Read(bytes)
	for k, v := range bytes {
		bytes[k] = dictionary[v%byte(len(dictionary))]
	}
	return string(bytes)
}
<|endoftext|>


<commit_before>// Package Bittrex is an implementation of the Biitrex API (public and private).
package bittrex

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const (
	API_BASE                   = "https://bittrex.com/api/" // Bittrex API endpoint
	API_VERSION                = "v1.1"                     // Bittrex API version
	DEFAULT_HTTPCLIENT_TIMEOUT = 30                         // HTTP client timeout
)

// New return a instanciate bittrex struct
func New(apiKey, apiSecret string) *Bittrex {
	client := NewClient(apiKey, apiSecret)
	return &Bittrex{client}
}

// handleErr gets JSON response from Bittrex API en deal with error
func handleErr(r jsonResponse) error {
	if !r.Success {
		return errors.New(r.Message)
	}
	return nil
}

// bittrex represent a bittrex client
type Bittrex struct {
	client *client
}

// GetMarkets is used to get the open and available trading markets at Bittrex along with other meta data.
func (b *Bittrex) GetMarkets() (markets []Market, err error) {
	r, err := b.client.do("GET", "public/getmarkets", "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &markets)
	return
}

// GetTicker is used to get the current ticker values for a market.
func (b *Bittrex) GetTicker(market string) (ticker Ticker, err error) {
	r, err := b.client.do("GET", "public/getticker?market="+strings.ToUpper(market), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &ticker)
	return
}

// GetMarketSummaries is used to get the last 24 hour summary of all active exchanges
func (b *Bittrex) GetMarketSummaries() (marketSummaries []MarketSummary, err error) {
	r, err := b.client.do("GET", "public/getmarketsummaries", "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &marketSummaries)
	return
}

// GetOrderBook is used to get retrieve the orderbook for a given market
// market: a string literal for the market (ex: BTC-LTC)
// cat: buy, sell or both to identify the type of orderbook to return.
// depth: how deep of an order book to retrieve. Max is 100
func (b *Bittrex) GetOrderBook(market, cat string, depth int) (orderBook OrderBook, err error) {
	if cat != "buy" && cat != "sell" && cat != "both" {
		cat = "both"
	}
	if depth > 100 {
		depth = 100
	}
	if depth < 1 {
		depth = 1
	}
	r, err := b.client.do("GET", fmt.Sprintf("public/getorderbook?market=%s&type=%s&depth=%d", strings.ToUpper(market), cat, depth), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &orderBook)
	return
}

// GetMarketHistory is used to retrieve the latest trades that have occured for a specific market.
// mark a string literal for the market (ex: BTC-LTC)
// count a number between 1-100 for the number of entries to return
func (b *Bittrex) GetMarketHistory(market string, count int) (trades []Trade, err error) {
	if count > 100 {
		count = 100
	}
	if count < 1 {
		count = 1
	}
	r, err := b.client.do("GET", fmt.Sprintf("public/getmarkethistory?market=%s&count=%d", strings.ToUpper(market), count), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &trades)
	return
}

// Market

// BuyLimit is used to place a limited buy order in a specific market.
func (b *Bittrex) BuyLimit(market string, quantity, rate float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/buylimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&rate="+strconv.FormatFloat(rate, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// BuyMarket is used to place a market buy order in a spacific market.
func (b *Bittrex) BuyMarket(market string, quantity float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/buymarket?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// SellLimit is used to place a limited sell order in a specific market.
func (b *Bittrex) SellLimit(market string, quantity, rate float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/selllimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&rate="+strconv.FormatFloat(rate, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// SellMarket is used to place a market sell order in a specific market.
func (b *Bittrex) SellMarket(market string, quantity float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/selllimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// CancelOrder is used to cancel a buy or sell order.
func (b *Bittrex) CancelOrder(orderID string) (err error) {
	r, err := b.client.do("GET", "market/cancel?uuid="+orderID, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	err = handleErr(response)
	return
}

// GetOpenOrders returns orders that you currently have opened.
// If market is set to "all", GetOpenOrders return all orders
// If market is set to a specific order, GetOpenOrders return orders for this market
func (b *Bittrex) GetOpenOrders(market string) (openOrders []Order, err error) {
	ressource := "market/getopenorders"
	if market != "all" {
		ressource += "?market=" + strings.ToUpper(market)
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &openOrders)
	return
}

// Account

// GetBalances is used to retrieve all balances from your account
func (b *Bittrex) GetBalances() (balances map[string]Balance, err error) {
	r, err := b.client.do("GET", "account/getbalances", "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &balances)
	return
}

// Getbalance is used to retrieve the balance from your account for a specific currency.
// currency: a string literal for the currency (ex: LTC)
func (b *Bittrex) GetBalance(currency string) (balance Balance, err error) {
	r, err := b.client.do("GET", "account/getbalance?currency="+strings.ToUpper(currency), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &balance)
	return
}

// GetDepositAddress is sed to generate or retrieve an address for a specific currency.
// currency a string literal for the currency (ie. BTC)
func (b *Bittrex) GetDepositAddress(currency string) (address Address, err error) {
	r, err := b.client.do("GET", "account/getdepositaddress?currency="+strings.ToUpper(currency), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &address)
	return
}

// Withdraw is used to withdraw funds from your account.
// address string the address where to send the funds.
// currency string literal for the currency (ie. BTC)
// quantity float the quantity of coins to withdraw
func (b *Bittrex) Withdraw(address, currency string, quantity float64) (withdrawUuid string, err error) {
	r, err := b.client.do("GET", "account/withdraw?currency="+strings.ToUpper(currency)+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&address="+address, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	withdrawUuid = u.Id
	return
}

// GetOrderHistory used to retrieve your order history.
// market string literal for the market (ie. BTC-LTC). If set to "all", will return for all market
// count int : 	the number of records to return. Is set to 0, will return max history
func (b *Bittrex) GetOrderHistory(market string, count int) (orders []Order, err error) {
	ressource := "account/getorderhistory"
	if count != 0 || market != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if market != "all" {
		ressource += "market=" + market
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &orders)
	return
}

// GetWithdrawalHistory is used to retrieve your withdrawal history
// currency string a string literal for the currency (ie. BTC). If set to "all", will return for all currencies
// count int the number of records to return. Is set to 0 will return the max set.
func (b *Bittrex) GetWithdrawalHistory(currency string, count int) (withdrawals []Withdrawal, err error) {
	ressource := "account/getwithdrawalhistory"
	if count != 0 || currency != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if currency != "all" {
		ressource += "currency=" + currency
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &withdrawals)
	return
}

// GetDepositHistory is used to retrieve your deposit history
// currency string a string literal for the currency (ie. BTC). If set to "all", will return for all currencies
// count int the number of records to return. Is set to 0 will return the max set.
func (b *Bittrex) GetDepositHistory(currency string, count int) (deposits []Deposit, err error) {
	ressource := "account/getdeposithistory"
	if count != 0 || currency != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if currency != "all" {
		ressource += "currency=" + currency
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &deposits)
	return
}
<commit_msg>Fix GetBalances<commit_after>// Package Bittrex is an implementation of the Biitrex API in Golang.
package bittrex

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"strings"
)

const (
	API_BASE                   = "https://bittrex.com/api/" // Bittrex API endpoint
	API_VERSION                = "v1.1"                     // Bittrex API version
	DEFAULT_HTTPCLIENT_TIMEOUT = 30                         // HTTP client timeout
)

// New return a instanciate bittrex struct
func New(apiKey, apiSecret string) *Bittrex {
	client := NewClient(apiKey, apiSecret)
	return &Bittrex{client}
}

// handleErr gets JSON response from Bittrex API en deal with error
func handleErr(r jsonResponse) error {
	if !r.Success {
		return errors.New(r.Message)
	}
	return nil
}

// bittrex represent a bittrex client
type Bittrex struct {
	client *client
}

// GetMarkets is used to get the open and available trading markets at Bittrex along with other meta data.
func (b *Bittrex) GetMarkets() (markets []Market, err error) {
	r, err := b.client.do("GET", "public/getmarkets", "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &markets)
	return
}

// GetTicker is used to get the current ticker values for a market.
func (b *Bittrex) GetTicker(market string) (ticker Ticker, err error) {
	r, err := b.client.do("GET", "public/getticker?market="+strings.ToUpper(market), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &ticker)
	return
}

// GetMarketSummaries is used to get the last 24 hour summary of all active exchanges
func (b *Bittrex) GetMarketSummaries() (marketSummaries []MarketSummary, err error) {
	r, err := b.client.do("GET", "public/getmarketsummaries", "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &marketSummaries)
	return
}

// GetOrderBook is used to get retrieve the orderbook for a given market
// market: a string literal for the market (ex: BTC-LTC)
// cat: buy, sell or both to identify the type of orderbook to return.
// depth: how deep of an order book to retrieve. Max is 100
func (b *Bittrex) GetOrderBook(market, cat string, depth int) (orderBook OrderBook, err error) {
	if cat != "buy" && cat != "sell" && cat != "both" {
		cat = "both"
	}
	if depth > 100 {
		depth = 100
	}
	if depth < 1 {
		depth = 1
	}
	r, err := b.client.do("GET", fmt.Sprintf("public/getorderbook?market=%s&type=%s&depth=%d", strings.ToUpper(market), cat, depth), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &orderBook)
	return
}

// GetMarketHistory is used to retrieve the latest trades that have occured for a specific market.
// mark a string literal for the market (ex: BTC-LTC)
// count a number between 1-100 for the number of entries to return
func (b *Bittrex) GetMarketHistory(market string, count int) (trades []Trade, err error) {
	if count > 100 {
		count = 100
	}
	if count < 1 {
		count = 1
	}
	r, err := b.client.do("GET", fmt.Sprintf("public/getmarkethistory?market=%s&count=%d", strings.ToUpper(market), count), "", false)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &trades)
	return
}

// Market

// BuyLimit is used to place a limited buy order in a specific market.
func (b *Bittrex) BuyLimit(market string, quantity, rate float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/buylimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&rate="+strconv.FormatFloat(rate, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// BuyMarket is used to place a market buy order in a spacific market.
func (b *Bittrex) BuyMarket(market string, quantity float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/buymarket?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// SellLimit is used to place a limited sell order in a specific market.
func (b *Bittrex) SellLimit(market string, quantity, rate float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/selllimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&rate="+strconv.FormatFloat(rate, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// SellMarket is used to place a market sell order in a specific market.
func (b *Bittrex) SellMarket(market string, quantity float64) (uuid string, err error) {
	r, err := b.client.do("GET", "market/selllimit?market="+market+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	uuid = u.Id
	return
}

// CancelOrder is used to cancel a buy or sell order.
func (b *Bittrex) CancelOrder(orderID string) (err error) {
	r, err := b.client.do("GET", "market/cancel?uuid="+orderID, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	err = handleErr(response)
	return
}

// GetOpenOrders returns orders that you currently have opened.
// If market is set to "all", GetOpenOrders return all orders
// If market is set to a specific order, GetOpenOrders return orders for this market
func (b *Bittrex) GetOpenOrders(market string) (openOrders []Order, err error) {
	ressource := "market/getopenorders"
	if market != "all" {
		ressource += "?market=" + strings.ToUpper(market)
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &openOrders)
	return
}

// Account

// GetBalances is used to retrieve all balances from your account
func (b *Bittrex) GetBalances() (balances []Balance, err error) {
	r, err := b.client.do("GET", "account/getbalances", "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &balances)
	return
}

// Getbalance is used to retrieve the balance from your account for a specific currency.
// currency: a string literal for the currency (ex: LTC)
func (b *Bittrex) GetBalance(currency string) (balance Balance, err error) {
	r, err := b.client.do("GET", "account/getbalance?currency="+strings.ToUpper(currency), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &balance)
	return
}

// GetDepositAddress is sed to generate or retrieve an address for a specific currency.
// currency a string literal for the currency (ie. BTC)
func (b *Bittrex) GetDepositAddress(currency string) (address Address, err error) {
	r, err := b.client.do("GET", "account/getdepositaddress?currency="+strings.ToUpper(currency), "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &address)
	return
}

// Withdraw is used to withdraw funds from your account.
// address string the address where to send the funds.
// currency string literal for the currency (ie. BTC)
// quantity float the quantity of coins to withdraw
func (b *Bittrex) Withdraw(address, currency string, quantity float64) (withdrawUuid string, err error) {
	r, err := b.client.do("GET", "account/withdraw?currency="+strings.ToUpper(currency)+"&quantity="+strconv.FormatFloat(quantity, 'f', 8, 64)+"&address="+address, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	var u Uuid
	err = json.Unmarshal(response.Result, &u)
	withdrawUuid = u.Id
	return
}

// GetOrderHistory used to retrieve your order history.
// market string literal for the market (ie. BTC-LTC). If set to "all", will return for all market
// count int : 	the number of records to return. Is set to 0, will return max history
func (b *Bittrex) GetOrderHistory(market string, count int) (orders []Order, err error) {
	ressource := "account/getorderhistory"
	if count != 0 || market != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if market != "all" {
		ressource += "market=" + market
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &orders)
	return
}

// GetWithdrawalHistory is used to retrieve your withdrawal history
// currency string a string literal for the currency (ie. BTC). If set to "all", will return for all currencies
// count int the number of records to return. Is set to 0 will return the max set.
func (b *Bittrex) GetWithdrawalHistory(currency string, count int) (withdrawals []Withdrawal, err error) {
	ressource := "account/getwithdrawalhistory"
	if count != 0 || currency != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if currency != "all" {
		ressource += "currency=" + currency
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &withdrawals)
	return
}

// GetDepositHistory is used to retrieve your deposit history
// currency string a string literal for the currency (ie. BTC). If set to "all", will return for all currencies
// count int the number of records to return. Is set to 0 will return the max set.
func (b *Bittrex) GetDepositHistory(currency string, count int) (deposits []Deposit, err error) {
	ressource := "account/getdeposithistory"
	if count != 0 || currency != "all" {
		ressource += "?"
	}
	if count != 0 {
		ressource += fmt.Sprintf("count=%d&", count)
	}
	if currency != "all" {
		ressource += "currency=" + currency
	}
	r, err := b.client.do("GET", ressource, "", true)
	if err != nil {
		return
	}
	var response jsonResponse
	if err = json.Unmarshal(r, &response); err != nil {
		return
	}
	if err = handleErr(response); err != nil {
		return
	}
	err = json.Unmarshal(response.Result, &deposits)
	return
}
<|endoftext|>


<commit_before>package gpio

import (
	"fmt"
	"io"
	"log"
	"os"
	"syscall"
	"time"
	"unsafe"

	"github.com/mkch/gpio/internal/fdevents"
	"github.com/mkch/gpio/internal/sys"
	"golang.org/x/sys/unix"
)

var Logger *log.Logger = log.New(os.Stderr, "gpio: ", log.LstdFlags)

// LineWithEvent is an opened GPIO line whose events can be subscribed.
type LineWithEvent struct {
	l      Line
	events *fdevents.FdEvents
}

func (l *LineWithEvent) Close() (err error) {
	err1 := l.l.Close()
	err2 := l.events.Close()
	if err1 != nil {
		return err1
	}
	return err2

}

// Value returns the current value of the GPIO line. 1 (high) or 0 (low).
func (l *LineWithEvent) Value() (value byte, err error) {
	return l.l.Value()
}

func readGPIOLineEventFd(fd int) time.Time {
	var eventData sys.GPIOEventData
	_, err := io.ReadFull(sys.FdReader(fd), (*[unsafe.Sizeof(eventData)]byte)(unsafe.Pointer(&eventData))[:])
	if err != nil {
		if err == syscall.EINTR {
			return time.Now() // Hack here.
		}
		Logger.Panic(fmt.Errorf("failed to read GPIO event: %w", err))
	}

	sec := uint64(time.Nanosecond) * eventData.Timestamp / uint64(time.Second)
	nano := uint64(time.Nanosecond) * eventData.Timestamp % uint64(time.Second)
	return time.Unix(int64(sec), int64(nano))
}

func newInputLineWithEvents(chipFd int, offset uint32, flags, eventFlags uint32, consumer string) (line *LineWithEvent, err error) {
	var req = sys.GPIOEventRequest{
		LineOffset:  offset,
		HandleFlags: uint32(flags),
		EventFlags:  uint32(eventFlags)}
	copy(req.ConsumerLabel[:], consumer)
	err = sys.Ioctl(chipFd, sys.GPIO_GET_LINEEVENT_IOCTL, uintptr(unsafe.Pointer(&req)))
	if err != nil {
		err = fmt.Errorf("request GPIO event failed: ioctl %w", err)
		return
	}
	events, err := fdevents.New(int(req.Fd), unix.EPOLLIN|unix.EPOLLPRI|unix.EPOLLET, readGPIOLineEventFd)
	if err != nil {
		unix.Close(int(req.Fd))
		return
	}

	line = &LineWithEvent{
		l:      Line{fd: int(req.Fd), numLines: 1},
		events: events,
	}
	return
}

// Events returns an channel from which the occurrence time of GPIO events can be read.
// The best estimate of time of event occurrence is sent to the returned channel,
// and the channel is closed when l is closed.
//
// Package gpio will not block sending to the channel: it only keeps the lastest
// value in the channel.
func (l *LineWithEvent) Events() <-chan time.Time {
	return l.events.Events()
}
<commit_msg>Fix double closing introduced by FdEvents.<commit_after>package gpio

import (
	"fmt"
	"io"
	"log"
	"os"
	"syscall"
	"time"
	"unsafe"

	"github.com/mkch/gpio/internal/fdevents"
	"github.com/mkch/gpio/internal/sys"
	"golang.org/x/sys/unix"
)

var Logger *log.Logger = log.New(os.Stderr, "gpio: ", log.LstdFlags)

// LineWithEvent is an opened GPIO line whose events can be subscribed.
type LineWithEvent struct {
	l      Line
	events *fdevents.FdEvents
}

func (l *LineWithEvent) Close() (err error) {
	err1 := l.l.Close()
	err2 := l.events.Close()
	if err1 != nil {
		return err1
	}
	return err2

}

// Value returns the current value of the GPIO line. 1 (high) or 0 (low).
func (l *LineWithEvent) Value() (value byte, err error) {
	return l.l.Value()
}

func readGPIOLineEventFd(fd int) time.Time {
	var eventData sys.GPIOEventData
	_, err := io.ReadFull(sys.FdReader(fd), (*[unsafe.Sizeof(eventData)]byte)(unsafe.Pointer(&eventData))[:])
	if err != nil {
		if err == syscall.EINTR {
			return time.Now() // Hack here.
		}
		Logger.Panic(fmt.Errorf("failed to read GPIO event: %w", err))
	}

	sec := uint64(time.Nanosecond) * eventData.Timestamp / uint64(time.Second)
	nano := uint64(time.Nanosecond) * eventData.Timestamp % uint64(time.Second)
	return time.Unix(int64(sec), int64(nano))
}

func newInputLineWithEvents(chipFd int, offset uint32, flags, eventFlags uint32, consumer string) (line *LineWithEvent, err error) {
	var req = sys.GPIOEventRequest{
		LineOffset:  offset,
		HandleFlags: uint32(flags),
		EventFlags:  uint32(eventFlags)}
	copy(req.ConsumerLabel[:], consumer)
	err = sys.Ioctl(chipFd, sys.GPIO_GET_LINEEVENT_IOCTL, uintptr(unsafe.Pointer(&req)))
	if err != nil {
		err = fmt.Errorf("request GPIO event failed: ioctl %w", err)
		return
	}
	events, err := fdevents.New(int(req.Fd), unix.EPOLLIN|unix.EPOLLPRI|unix.EPOLLET, readGPIOLineEventFd)
	if err != nil {
		unix.Close(int(req.Fd))
		return
	}

	fd2, err := unix.Dup(int(req.Fd))
	if err != nil {
		err = fmt.Errorf("request GPIO event failed: dup %w", err)
		return
	}
	line = &LineWithEvent{
		l:      Line{fd: fd2, numLines: 1},
		events: events,
	}
	return
}

// Events returns an channel from which the occurrence time of GPIO events can be read.
// The best estimate of time of event occurrence is sent to the returned channel,
// and the channel is closed when l is closed.
//
// Package gpio will not block sending to the channel: it only keeps the lastest
// value in the channel.
func (l *LineWithEvent) Events() <-chan time.Time {
	return l.events.Events()
}
<|endoftext|>


<commit_before>package gorouter_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/vardius/gorouter"
)

func Example() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// Hello, guest!
}

func ExampleMiddlewareFunc_global() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	// apply middlewares to all routes
	// can pass as many as you want
	router := gorouter.New(logger)
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleMiddlewareFunc_route() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// apply middlewares to route and all it children
	// can pass as many as you want
	router.USE("GET", "/hello/{name}", logger)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleMiddlewareFunc_method() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// apply middlewares to all routes with GET method
	// can pass as many as you want
	router.USE("GET", "", logger)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleRouter_mount() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	subrouter := gorouter.New()
	subrouter.GET("/{name}", http.HandlerFunc(hello))

	router := gorouter.New()
	router.Mount("/hello", subrouter)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// Hello, guest!
}
<commit_msg>Add subrouter another example<commit_after>package gorouter_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/vardius/gorouter"
)

func Example() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// Hello, guest!
}

func ExampleMiddlewareFunc() {
	// Global middleware example
	// applies to all routes
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	// apply middlewares to all routes
	// can pass as many as you want
	router := gorouter.New(logger)
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleMiddlewareFunc_second() {
	// Route level middleware example
	// applies to route and its lower tree
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// apply middlewares to route and all it children
	// can pass as many as you want
	router.USE("GET", "/hello/{name}", logger)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleMiddlewareFunc_third() {
	// Http method middleware example
	// applies to all routes under this method
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	logger := func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			fmt.Printf("[%s] %q\n", r.Method, r.URL.String())
			next.ServeHTTP(w, r)
		}

		return http.HandlerFunc(fn)
	}

	router := gorouter.New()
	router.GET("/hello/{name}", http.HandlerFunc(hello))

	// apply middlewares to all routes with GET method
	// can pass as many as you want
	router.USE("GET", "", logger)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// [GET] "/hello/guest"
	// Hello, guest!
}

func ExampleRouter_mount() {
	hello := func(w http.ResponseWriter, r *http.Request) {
		params, _ := gorouter.FromContext(r.Context())
		fmt.Printf("Hello, %s!\n", params.Value("name"))
	}

	subrouter := gorouter.New()
	subrouter.GET("/{name}", http.HandlerFunc(hello))

	router := gorouter.New()
	router.Mount("/hello", subrouter)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// Hello, guest!
}

func ExampleRouter_mount_second() {
	subrouter := http.NewServeMux()
	subrouter.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
		fmt.Println("Hello, guest!")
	})

	router := gorouter.New()
	router.Mount("/hello", subrouter)

	// Normally you would call ListenAndServe starting an HTTP server
	// with a given address and router as a handler
	// log.Fatal(http.ListenAndServe(":8080", router))
	// but for this example we will mock request

	w := httptest.NewRecorder()
	req, err := http.NewRequest(gorouter.GET, "/hello/guest", nil)
	if err != nil {
		return
	}

	router.ServeHTTP(w, req)

	// Output:
	// Hello, guest!
}
<|endoftext|>


<commit_before>package assets

import (
	"os"
)

func ExampleGenerator() {
	g := Generator{
		PackageName:  "main",
		VariableName: "MyAssets",
		Compressed:   true,
		StripPrefix:  ".",
	}

	if err := g.AddDir("."); err != nil {
		panic(err)
	}

	// This will write a go file to standard out. The generated go file
	// will reside in the g.PackageName package and will contain a
	// single variable g.VariableName of type assets.FileSystem containing
	// the whole file system.
	g.Write(os.Stdout)
}
<commit_msg>Simplified example<commit_after>package assets

import (
	"os"
)

func ExampleGenerator() {
	g := Generator{}

	if err := g.AddDir("."); err != nil {
		panic(err)
	}

	// This will write a go file to standard out. The generated go file
	// will reside in the g.PackageName package and will contain a
	// single variable g.VariableName of type assets.FileSystem containing
	// the whole file system.
	g.Write(os.Stdout)
}
<|endoftext|>


<commit_before>package jsonseq_test

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/jmank88/jsonseq"
)

func ExampleWriteRecord() {
	_ = jsonseq.WriteRecord(os.Stdout, []byte(`{"id":1}`))
	_ = jsonseq.WriteRecord(os.Stdout, []byte(`{"id":2}`))
	_ = jsonseq.WriteRecord(os.Stdout, []byte(`{"id":3}`))

	// Output:
	// {"id":1}
	// {"id":2}
	// {"id":3}
	//
}

func ExampleNewEncoder() {
	encoder := jsonseq.NewEncoder(os.Stdout)
	_ = encoder.Encode("Test")
	_ = encoder.Encode(123.456)
	_ = encoder.Encode(struct{ Id int }{Id: 1})

	// Output:
	// "Test"
	// 123.456
	// {"Id":1}
	//
}

func ExampleDecoder_Decode() {
	d := jsonseq.NewDecoder(strings.NewReader(`{"id":1} 12341234 true discarded junk`))
	for {
		var i interface{}
		if err := d.Decode(&i); err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println(err)
		} else {
			fmt.Println(i)
		}
	}

	// Output:
	// map[id:1]
	// invalid record: "1234"
	// 1234
	// true
}
<commit_msg>fix vet<commit_after>package jsonseq

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func ExampleWriteRecord() {
	_ = WriteRecord(os.Stdout, []byte(`{"id":1}`))
	_ = WriteRecord(os.Stdout, []byte(`{"id":2}`))
	_ = WriteRecord(os.Stdout, []byte(`{"id":3}`))

	// Output:
	// {"id":1}
	// {"id":2}
	// {"id":3}
	//
}

func ExampleNewEncoder() {
	encoder := NewEncoder(os.Stdout)
	_ = encoder.Encode("Test")
	_ = encoder.Encode(123.456)
	_ = encoder.Encode(struct{ Id int }{Id: 1})

	// Output:
	// "Test"
	// 123.456
	// {"Id":1}
	//
}

func ExampleDecoder_Decode() {
	d := NewDecoder(strings.NewReader(`{"id":1} 12341234 true discarded junk`))
	for {
		var i interface{}
		if err := d.Decode(&i); err != nil {
			if err == io.EOF {
				break
			}
			fmt.Println(err)
		} else {
			fmt.Println(i)
		}
	}

	// Output:
	// map[id:1]
	// invalid record: "1234"
	// 1234
	// true
}
<|endoftext|>


<commit_before>/*
Copyright 2018 The Jetstack cert-manager contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package validation

import (
	"reflect"
	"testing"

	"github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1"
	"github.com/jetstack/cert-manager/test/util/generate"
	"k8s.io/apimachinery/pkg/util/validation/field"
)

const (
	defaultTestIssuerName = "test-issuer"
	defaultTestCrtName    = "test-crt"
	defaultTestNamespace  = "default"
)

func TestValidateCertificateForIssuer(t *testing.T) {
	fldPath := field.NewPath("spec")

	scenarios := map[string]struct {
		crt    *v1alpha1.Certificate
		issuer *v1alpha1.Issuer
		errs   []*field.Error
	}{
		"valid basic certificate": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					IssuerRef: validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},

			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
		},
		"certificate with invalid keyAlgorithm": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.KeyAlgorithm("blah"),
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
			errs: []*field.Error{
				field.Invalid(fldPath.Child("keyAlgorithm"), v1alpha1.KeyAlgorithm("blah"), "ACME key algorithm must be RSA"),
			},
		},
		"certificate with correct keyAlgorithm for ACME": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.RSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
		},
		"certificate with incorrect keyAlgorithm for ACME": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.ECDSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
			errs: []*field.Error{
				field.Invalid(fldPath.Child("keyAlgorithm"), v1alpha1.ECDSAKeyAlgorithm, "ACME key algorithm must be RSA"),
			},
		},
		"certificate with unspecified issuer type": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.ECDSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: &v1alpha1.Issuer{},
			errs: []*field.Error{
				field.Invalid(fldPath, "no issuer specified for Issuer '/'", "no issuer specified for Issuer '/'"),
			},
		},
	}
	for n, s := range scenarios {
		t.Run(n, func(t *testing.T) {
			errs := ValidateCertificateForIssuer(s.crt, s.issuer)
			if len(errs) != len(s.errs) {
				t.Errorf("Expected %v but got %v", s.errs, errs)
				return
			}
			for i, e := range errs {
				expectedErr := s.errs[i]
				if !reflect.DeepEqual(e, expectedErr) {
					t.Errorf("Expected %v but got %v", expectedErr, e)
				}
			}
		})
	}
}
<commit_msg>Add test case that should fail acme validation<commit_after>/*
Copyright 2018 The Jetstack cert-manager contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package validation

import (
	"reflect"
	"testing"

	"github.com/jetstack/cert-manager/pkg/apis/certmanager/v1alpha1"
	"github.com/jetstack/cert-manager/test/util/generate"
	"k8s.io/apimachinery/pkg/util/validation/field"
)

const (
	defaultTestIssuerName = "test-issuer"
	defaultTestCrtName    = "test-crt"
	defaultTestNamespace  = "default"
)

func TestValidateCertificateForIssuer(t *testing.T) {
	fldPath := field.NewPath("spec")

	scenarios := map[string]struct {
		crt    *v1alpha1.Certificate
		issuer *v1alpha1.Issuer
		errs   []*field.Error
	}{
		"valid basic certificate": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					IssuerRef: validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},

			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
		},
		"certificate with invalid keyAlgorithm": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.KeyAlgorithm("blah"),
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
			errs: []*field.Error{
				field.Invalid(fldPath.Child("keyAlgorithm"), v1alpha1.KeyAlgorithm("blah"), "ACME key algorithm must be RSA"),
			},
		},
		"certificate with correct keyAlgorithm for ACME": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.RSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
		},
		"certificate with incorrect keyAlgorithm for ACME": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.ECDSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
			errs: []*field.Error{
				field.Invalid(fldPath.Child("keyAlgorithm"), v1alpha1.ECDSAKeyAlgorithm, "ACME key algorithm must be RSA"),
			},
		},
		"acme certificate with organization set": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					Organization: "shouldfailorg",
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: generate.Issuer(generate.IssuerConfig{
				Name:      defaultTestIssuerName,
				Namespace: defaultTestNamespace,
			}),
			errs: []*field.Error{
				field.Invalid(fldPath.Child("organization"), "shouldfailorg", "ACME does not support setting the organization name"),
			},
		},
		"certificate with unspecified issuer type": {
			crt: &v1alpha1.Certificate{
				Spec: v1alpha1.CertificateSpec{
					KeyAlgorithm: v1alpha1.ECDSAKeyAlgorithm,
					IssuerRef:    validIssuerRef,
					ACME: &v1alpha1.ACMECertificateConfig{
						Config: []v1alpha1.DomainSolverConfig{
							{
								Domains: []string{"example.com"},
								SolverConfig: v1alpha1.SolverConfig{
									HTTP01: &v1alpha1.HTTP01SolverConfig{},
								},
							},
						},
					},
				},
			},
			issuer: &v1alpha1.Issuer{},
			errs: []*field.Error{
				field.Invalid(fldPath, "no issuer specified for Issuer '/'", "no issuer specified for Issuer '/'"),
			},
		},
	}
	for n, s := range scenarios {
		t.Run(n, func(t *testing.T) {
			errs := ValidateCertificateForIssuer(s.crt, s.issuer)
			if len(errs) != len(s.errs) {
				t.Errorf("Expected %v but got %v", s.errs, errs)
				return
			}
			for i, e := range errs {
				expectedErr := s.errs[i]
				if !reflect.DeepEqual(e, expectedErr) {
					t.Errorf("Expected %v but got %v", expectedErr, e)
				}
			}
		})
	}
}
<|endoftext|>


<commit_before>package events

import (
	"context"

	"github.com/ohsu-comp-bio/funnel/proto/tes"
)

// TaskBuilder aggregates events into an in-memory Task object.
type TaskBuilder struct {
	*tes.Task
}

// WriteEvent updates the Task object.
func (tb TaskBuilder) WriteEvent(ctx context.Context, ev *Event) error {
	t := tb.Task
	t.Id = ev.Id
	attempt := int(ev.Attempt)
	index := int(ev.Index)

	switch ev.Type {
	case Type_TASK_STATE:
		to := ev.GetState()
		if err := tes.ValidateTransition(t.GetState(), ev.GetState()); err != nil {
			return err
		}
		t.State = to

	case Type_SYSTEM_LOG:
		t.GetTaskLog(attempt).SystemLogs = append(t.GetTaskLog(attempt).SystemLogs, ev.SysLogString())

	case Type_TASK_START_TIME:
		t.GetTaskLog(attempt).StartTime = ev.GetStartTime()

	case Type_TASK_END_TIME:
		t.GetTaskLog(attempt).EndTime = ev.GetEndTime()

	case Type_TASK_OUTPUTS:
		t.GetTaskLog(attempt).Outputs = ev.GetOutputs().Value

	case Type_TASK_METADATA:
		t.GetTaskLog(attempt).Metadata = ev.GetMetadata().Value

	case Type_EXECUTOR_START_TIME:
		t.GetExecLog(attempt, index).StartTime = ev.GetStartTime()

	case Type_EXECUTOR_END_TIME:
		t.GetExecLog(attempt, index).EndTime = ev.GetEndTime()

	case Type_EXECUTOR_EXIT_CODE:
		t.GetExecLog(attempt, index).ExitCode = ev.GetExitCode()

	case Type_EXECUTOR_STDOUT:
		t.GetExecLog(attempt, index).Stdout += ev.GetStdout()

	case Type_EXECUTOR_STDERR:
		t.GetExecLog(attempt, index).Stderr += ev.GetStderr()
	}

	return nil
}
<commit_msg>datastore: fix metadata event handling<commit_after>package events

import (
	"context"

	"github.com/ohsu-comp-bio/funnel/proto/tes"
)

// TaskBuilder aggregates events into an in-memory Task object.
type TaskBuilder struct {
	*tes.Task
}

// WriteEvent updates the Task object.
func (tb TaskBuilder) WriteEvent(ctx context.Context, ev *Event) error {
	t := tb.Task
	t.Id = ev.Id
	attempt := int(ev.Attempt)
	index := int(ev.Index)

	switch ev.Type {
	case Type_TASK_STATE:
		to := ev.GetState()
		if err := tes.ValidateTransition(t.GetState(), ev.GetState()); err != nil {
			return err
		}
		t.State = to

	case Type_SYSTEM_LOG:
		t.GetTaskLog(attempt).SystemLogs = append(t.GetTaskLog(attempt).SystemLogs, ev.SysLogString())

	case Type_TASK_START_TIME:
		t.GetTaskLog(attempt).StartTime = ev.GetStartTime()

	case Type_TASK_END_TIME:
		t.GetTaskLog(attempt).EndTime = ev.GetEndTime()

	case Type_TASK_OUTPUTS:
		t.GetTaskLog(attempt).Outputs = ev.GetOutputs().Value

	case Type_TASK_METADATA:
		if t.GetTaskLog(attempt).Metadata == nil {
			t.GetTaskLog(attempt).Metadata = map[string]string{}
		}
		for k, v := range ev.GetMetadata().Value {
			t.GetTaskLog(attempt).Metadata[k] = v
		}

	case Type_EXECUTOR_START_TIME:
		t.GetExecLog(attempt, index).StartTime = ev.GetStartTime()

	case Type_EXECUTOR_END_TIME:
		t.GetExecLog(attempt, index).EndTime = ev.GetEndTime()

	case Type_EXECUTOR_EXIT_CODE:
		t.GetExecLog(attempt, index).ExitCode = ev.GetExitCode()

	case Type_EXECUTOR_STDOUT:
		t.GetExecLog(attempt, index).Stdout += ev.GetStdout()

	case Type_EXECUTOR_STDERR:
		t.GetExecLog(attempt, index).Stderr += ev.GetStderr()
	}

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/go-zoo/bone"
)

var (
	mux = bone.New(Serve, Wrap)
)

func Wrap(mux *bone.Mux) *bone.Mux {
	return mux.Prefix("/api")
}

func Serve(mux *bone.Mux) *bone.Mux {
	mux.Serve = func(rw http.ResponseWriter, req *http.Request) {
		tr := time.Now()
		mux.DefaultServe(rw, req)
		fmt.Println("Serve request from", req.RemoteAddr, "in", time.Since(tr))
	}
	return mux
}

func main() {
	// Custom 404
	mux.NotFoundFunc(Handler404)
	// Handle with any http method, Handle takes http.Handler as argument.
	mux.Handle("/index", http.HandlerFunc(homeHandler))
	mux.Handle("/index/:var/info/:test", http.HandlerFunc(varHandler))
	// Get, Post etc... takes http.HandlerFunc as argument.
	mux.Post("/home", http.HandlerFunc(homeHandler))
	mux.Get("/home/:var", http.HandlerFunc(varHandler))

	mux.GetFunc("/test/*", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte(req.RequestURI))
	})

	// Start Listening
	log.Fatal(mux.ListenAndServe(":8080"))
}

func homeHandler(rw http.ResponseWriter, req *http.Request) {
	rw.Write([]byte("WELCOME HOME"))
}

func varHandler(rw http.ResponseWriter, req *http.Request) {
	varr := bone.GetValue(req, "var")
	test := bone.GetValue(req, "test")

	var args = struct {
		first  string
		second string
	}{varr, test}

	_ = json.NewEncoder(rw).Encode(&args)
}

func Handler404(rw http.ResponseWriter, req *http.Request) {
	rw.Write([]byte("These are not the droids you're looking for ..."))
}
<commit_msg>fixed example/001 json encoding bug<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"time"

	"github.com/go-zoo/bone"
)

var (
	mux = bone.New(Serve, Wrap)
)

func Wrap(mux *bone.Mux) *bone.Mux {
	return mux.Prefix("/api")
}

func Serve(mux *bone.Mux) *bone.Mux {
	mux.Serve = func(rw http.ResponseWriter, req *http.Request) {
		tr := time.Now()
		mux.DefaultServe(rw, req)
		fmt.Println("Serve request from", req.RemoteAddr, "in", time.Since(tr))
	}
	return mux
}

func main() {
	// Custom 404
	mux.NotFoundFunc(Handler404)
	// Handle with any http method, Handle takes http.Handler as argument.
	mux.Handle("/index", http.HandlerFunc(homeHandler))
	mux.Handle("/index/:var/info/:test", http.HandlerFunc(varHandler))
	// Get, Post etc... takes http.HandlerFunc as argument.
	mux.Post("/home", http.HandlerFunc(homeHandler))
	mux.Get("/home/:var", http.HandlerFunc(varHandler))

	mux.GetFunc("/test/*", func(rw http.ResponseWriter, req *http.Request) {
		rw.Write([]byte(req.RequestURI))
	})

	// Start Listening
	log.Fatal(mux.ListenAndServe(":8080"))
}

func homeHandler(rw http.ResponseWriter, req *http.Request) {
	rw.Write([]byte("WELCOME HOME"))
}

func varHandler(rw http.ResponseWriter, req *http.Request) {
	varr := bone.GetValue(req, "var")
	test := bone.GetValue(req, "test")

	var args = struct {
		First  string
		Second string
	}{varr, test}

	if err := json.NewEncoder(rw).Encode(&args); err != nil {
		panic(err)
	}
}

func Handler404(rw http.ResponseWriter, req *http.Request) {
	rw.Write([]byte("These are not the droids you're looking for ..."))
}
<|endoftext|>