Ejemplo n.º 1
0
Archivo: totp.go Proyecto: nzlov/totp
// BarcodeImage creates a QR code for use with Google Authenticator (GA).
// label is the string that GA uses in the UI. secretkey should be this user's
// secret key. opt should be the configured Options for this TOTP. If a nil
// options is passed, then DefaultOptions is used.
func BarcodeImage(label string, secretkey []byte, opt *Options) ([]byte, error) {
	if opt == nil {
		opt = DefaultOptions
	}

	u := &url.URL{
		Scheme: "otpauth",
		Host:   "totp",
		Path:   fmt.Sprintf("/%s", label),
	}

	params := url.Values{
		"secret": {base32.StdEncoding.EncodeToString(secretkey)},
		"digits": {strconv.Itoa(int(opt.Digits))},
		"period": {strconv.Itoa(int(opt.TimeStep / time.Second))},
	}

	u.RawQuery = params.Encode()

	c, err := qr.Encode(u.String(), qr.M)

	if err != nil {
		return nil, err
	}

	return c.PNG(), nil
}
Ejemplo n.º 2
0
func registerMFA(c *gobot.Context) {
	log.Debugf("registering mfa")
	c.Respond(fmt.Sprintf("registering a %s mfa", c.Match(1)))

	data := make([]byte, 10)
	if n, err := rand.Read(data); err != nil {
		c.Fail(err)
		return
	} else if n != len(data) {
		c.Fail(fmt.Errorf("read %d random bytes, wanted %d", n, len(data)))
		return
	}
	secret := base32.StdEncoding.EncodeToString(data)

	saveOtp(c.User, secret)

	code, err := qr.Encode("otpauth://totp/Gobot?secret="+secret, qr.Q)
	if err != nil {
		c.Fail(err)
		return
	}

	c.Upload(gobot.Attachment{
		Title:       "QR Code",
		Filename:    "QR.png",
		Content:     bytes.NewReader(code.PNG()),
		ContentType: "image/png",
	})
}
Ejemplo n.º 3
0
func (s *Server) QRHandler(path string) http.Handler {
	handler := func(w http.ResponseWriter, r *http.Request) {
		url := ""

		if r.TLS == nil {
			url += "qrl://"
		} else {
			url += "sqrl://"
		}

		url += r.Host
		url += "/" + path + "?"
		url += r.URL.RawQuery
		url += "&nut="
		url += s.nonce.Generate(r.RemoteAddr)

		// w.Header().Add("Content-Type", "text/html")
		// io.WriteString(w, fmt.Sprintf("%#v<br/><br/>", url))
		// io.WriteString(w, fmt.Sprintf("%#v<br/><br/>", *r.URL))
		// io.WriteString(w, fmt.Sprintf("%#v<br/><br/>", *r))

		w.Header().Add("Content-Type", "image/png")
		qrcode, err := qr.Encode(url, qr.M)

		if err != nil {
			return
		}

		w.Write(qrcode.PNG())
	}

	return http.HandlerFunc(handler)
}
Ejemplo n.º 4
0
func main() {
	var src, dst string
	switch len(os.Args) {
	case 1:
		log.Fatal("Source string must be given!")
	case 2:
		src = os.Args[1]
		dst = "qr.png"
	case 3:
		src = os.Args[1]
		dst = os.Args[2]
	default:
		log.Fatal("Invalid arguments!")
	}

	code, err := qr.Encode(src, qr.M)
	if err != nil {
		log.Fatal(err)
	}

	err = ioutil.WriteFile(dst, code.PNG(), 0644)
	if err != nil {
		log.Fatal(err)
	}
}
Ejemplo n.º 5
0
// GenTicket - Sign the ticket number provided through the URL and Generate a QR Code
func GenTicket(w http.ResponseWriter, r *http.Request) {
	var buffer bytes.Buffer

	// Load the variables from the path using mux
	vars := mux.Vars(r)

	// Setup the Ticket and sign it
	var ticketnum = TicketNumber{ID: []byte(vars["hash"])}
	ticketnum.sign()

	// Generate the text string to encode
	buffer.WriteString(ticketnum.Sig1.String())
	buffer.WriteString("/")
	buffer.WriteString(ticketnum.Sig2.String())
	buffer.WriteString("/")
	buffer.WriteString(vars["hash"])

	// Generate the QR code for the hash and two signatures
	code, err := qr.Encode(buffer.String(), qr.H)
	if err != nil {
		panic(err)
	}

	imgByte := code.PNG()

	w.Header().Set("Content-Type", "image/png")
	w.WriteHeader(http.StatusOK)
	w.Write(imgByte)

	//	fmt.Fprintf(w, "sig1: %#v \n sig2: %#v \n message: %#v",ticketnum.Sig1,ticketnum.Sig2,vars["hash"])
}
Ejemplo n.º 6
0
// PixelRelay://scan?host=HOSTURL&album=ALBUMNAME&privatekey=PRIVATEKEY
func createQR(album, key string) (qrname string) {

	qrname = strings.Join([]string{genQRName(album, key), "png"}, ".")
	qrpath := utils.ImageCfg.QR()
	qrtemp := strings.Join([]string{qrpath, qrname}, "")

	if Exists(qrtemp) {
		return
	}

	host := strings.Join([]string{utils.AppCfg.Url(), "up"}, "/")
	qrstr := fmt.Sprintf("PixelRelay://scan?host=%s&album=%s&privatekey=%s", host, album, key)

	c, err := qr.Encode(qrstr, qr.M)

	if err != nil {
		log.Println("qr err: ", err)
	}

	out, err := os.Create(qrtemp)
	if err != nil {
		log.Fatal(err)
	}
	defer out.Close()

	_, err = out.Write(c.PNG())
	if err != nil {
		panic(err)
	}

	return
}
Ejemplo n.º 7
0
func qrHandler(w http.ResponseWriter, r *http.Request) {

	uri := r.RequestURI

	// TODO(dgryski): handle /qr/ssid for an html page that renders the QR code with also instructions

	if !strings.HasPrefix(uri, "/qr/") || !strings.HasSuffix(uri, ".png") {
		http.NotFound(w, r)
		return
	}

	ssid := uri[len("/qr/") : len(uri)-len(".png")]

	dbmu.RLock()
	wifi, ok := db[ssid]
	dbmu.RUnlock()

	if !ok {
		http.NotFound(w, r)
		return
	}

	text := wifi.QRText()

	code, err := qr.Encode(text, qr.Q)
	if err != nil {
		log.Printf("error encoding: %q: %v", text, err)
		http.Error(w, "bad request", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-type", "image/png")
	w.Write(code.PNG())
}
Ejemplo n.º 8
0
// QR generates a byte slice containing the a QR code encoded as a
// PNG with level Q error correction.
func (otp *HOTP) QR(label string) ([]byte, error) {
	u := otp.URL(label)
	code, err := qr.Encode(u, qr.Q)
	if err != nil {
		return nil, err
	}
	return code.PNG(), nil
}
Ejemplo n.º 9
0
func generateQr(headers []string, row []string, pool chan bool, wg *sync.WaitGroup) {
	filename := row[*label]
	var text string

	//build the output string
	for index, value := range row {
		text += headers[index] + ": " + value + "\n"
	}

	// Encode string to QR codes
	code, err := qr.Encode(text, qr.M)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// convert code to rgba
	b := code.Size
	img := image.NewRGBA(image.Rect(0, 0, b*scale, b*scale))

	for x := 0; x < b; x++ {
		for y := 0; y < b; y++ {
			if code.Black(x, y) {
				draw.Draw(img, image.Rect(x*scale, y*scale, (x+1)*scale, (y+1)*scale), black, black.Bounds().Min, draw.Src)
			} else {
				draw.Draw(img, image.Rect(x*scale, y*scale, (x+1)*scale, (y+1)*scale), white, white.Bounds().Min, draw.Src)
			}
		}
	}

	// verify output dir
	if _, err := os.Stat(*outdir); err != nil {
		os.Mkdir(*outdir, 0666)
	}
	//save the imgByte to file
	filename = *outdir + "/" + filename + ".png"
	out, err := os.Create(filename)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	err = png.Encode(out, img)

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// everything ok
	fmt.Println("QR code generated and saved to " + filename)
	<-pool
	(*wg).Done()
}
Ejemplo n.º 10
0
// Generate a text string to a QR code, which you can write to a terminal or file.
func (c *Config) Generate(text string) (string, error) {
	code, err := qr.Encode(text, qr.Level(c.Level))
	if err != nil {
		return "", err
	}

	// calculate size in blocks
	// two bits per block
	// add one block for remaining singlebit (if existing)
	// add two blocks for border left and right
	size := code.Size/2 + (code.Size % 2) + 2

	// rune slice
	//++ TODO: precalculate size
	qrRunes := make([]rune, 0)

	// upper border
	c.addWhiteRow(&qrRunes, size)

	// content
	for y := 0; y < code.Size; y += 2 {
		if c.UseSGR {
			qrRunes = append(qrRunes, []rune(sgr.FgWhite+sgr.BgBlack)...)
		}
		qrRunes = append(qrRunes, '█')
		for x := 0; x < code.Size; x += 2 {
			var num int8
			if !code.Black(x, y) {
				num += 1
			}
			if !code.Black(x+1, y) {
				num += 2
			}
			if !code.Black(x, y+1) {
				num += 4
			}
			if !code.Black(x+1, y+1) {
				num += 8
			}
			qrRunes = append(qrRunes, blocks[num])
		}
		qrRunes = append(qrRunes, '█')
		if c.UseSGR {
			qrRunes = append(qrRunes, []rune(sgr.Reset)...)
		}
		qrRunes = append(qrRunes, '\n')
	}

	// add lower border when required (only required when QR size is odd)
	if code.Size%2 == 0 {
		c.addWhiteRow(&qrRunes, size)
	}

	return string(qrRunes), nil
}
Ejemplo n.º 11
0
func encode(message string) {
	c, err := qr.Encode(message, qr.L)

	if err != nil {
		fmt.Println(err)
	} else {
		pngdat := c.PNG()
		s := []string{"images/", message, ".png"}
		ioutil.WriteFile(strings.Join(s, ""), pngdat, 0666)
	}

}
Ejemplo n.º 12
0
// AddTicket - Adds a valid ticket for the event and stores it in the datastore
func AddTicket(w http.ResponseWriter, r *http.Request) {
	var buffer bytes.Buffer
	vars := mux.Vars(r)

	// Load the event datastore key
	event, err := datastore.DecodeKey(vars["eventId"])
	if err != nil {
		panic(err)
	}

	// Create an appengine context
	ctx := appengine.NewContext(r)
	// fmt.Fprintf("%#v",ctx)

	// Build the ticket entry
	t := Ticket{
		OrderID:  r.FormValue("order_id"),
		EventKey: event,
		Valid:    true,
	}

	// Store the ticket
	k, err := t.Store(ctx)
	if err != nil {
		panic(err)
	}

	// Create the Ticket Num
	var ticketnum = TicketNumber{ID: []byte(k.Encode())}
	ticketnum.sign()

	// Generate the text string to encode
	buffer.WriteString(ticketnum.Sig1.String())
	buffer.WriteString("/")
	buffer.WriteString(ticketnum.Sig2.String())
	buffer.WriteString("/")
	buffer.WriteString(string(k.Encode()))

	// Generate the QR code for the hash and two signatures
	code, err := qr.Encode(buffer.String(), qr.L)
	code.Scale = 2

	if err != nil {
		panic(err)
	}

	imgByte := code.PNG()
	w.Header().Set("Content-Type", "image/png")
	w.Header().Set("Content-Disposition", `inline; filename="`+k.Encode()+`"`)
	w.WriteHeader(http.StatusOK)
	w.Write(imgByte)
}
Ejemplo n.º 13
0
Archivo: test.go Proyecto: redage/apps
func viewHandler(w http.ResponseWriter, r *http.Request) {
	c, err := qr.Encode(r.FormValue("t"), qr.L)
	if err != nil {
	}
	pngdat := c.Image()
	//fmt.Println(pngdat.Bounds());
	//fmt.Println(c.Size);
	//fmt.Println(c.Scale);
	//to do resize
	newImage := resize.Resample(pngdat, image.Rect(0, 0, c.Size, c.Size), 120, 120)
	png.Encode(w, newImage)
	//png.Encode(w,pngdat);
}
Ejemplo n.º 14
0
// Encode makes a QR code out of data and encodes it into three
// different representations.
func Encode(data []byte) (*Encodings, error) {
	code, err := qr.Encode(string(data), qr.L)
	if err != nil {
		return nil, err
	}

	var result Encodings
	result.PNG = code.PNG()
	result.Terminal = terminal(code)
	result.ASCII = ascii(code)

	return &result, nil
}
Ejemplo n.º 15
0
func getNewUserSession_API(w http.ResponseWriter, req *http.Request) {
	data := req.FormValue("callbackdata")
	if data == "" {
		cod, err := qr.Encode(fmt.Sprintf("http://%s/api/v1/openTok3n/getIntegrationError", TOK3N_DOMAIN), qr.M)
		if err != nil {
			fmt.Fprintf(w, "Something went very wrong, verify OpenTok3n integration instalation")
			return
		}
		img := cod.PNG()
		w.Write(img)
		return
	}

	resp, err := http.PostForm(fmt.Sprintf("http://%s/api/v1/openTok3n/getNewUserSession", TOK3N_DOMAIN), url.Values{"kind": {"OTaccess"}, "secretKey": {configData.Tok3nAPISecret}})
	if err != nil {
		cod, err := qr.Encode(fmt.Sprintf("http://%s/api/v1/openTok3n/getIntegrationError", TOK3N_DOMAIN), qr.M)
		if err != nil {
			fmt.Fprintf(w, "Something went very wrong, verify OpenTok3n integration instalation")
			return
		}
		img := cod.PNG()
		w.Write(img)
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	addTok3nAuthenticationSeccion(string(body), data)

	cod, err := qr.Encode(fmt.Sprintf("http://%s/api/v1/openTok3n/validateNewUserSession?session=%s&key=%s", TOK3N_DOMAIN, body, configData.Tok3nAPIKey), qr.H)
	if err != nil {
		fmt.Fprintf(w, "Something whent very wrong, verify OpenTok3n integration instalation")
		return
	}
	img := cod.PNG()
	w.Header().Add("Content-Type", "image/png")
	w.Write(img)
}
Ejemplo n.º 16
0
Archivo: qr.go Proyecto: jango2015/wk
// Execute write qrcode image to response
func (qrcode *QrCodeResult) Execute(ctx *wk.HttpContext) error {

	c, err := qr.Encode(qrcode.Text, qr.M)
	if err != nil {
		log.Println("QrCodeResult Execute Error", err)
		return err
	}
	png := c.PNG()
	//ioutil.WriteFile(qrcode.Text+"_demo.png", png, 0666)
	ctx.ContentType("image/png")
	ctx.Write(png)

	return nil
}
Ejemplo n.º 17
0
func (ui *UIHandler) serveQR(rw http.ResponseWriter, req *http.Request) {
	url := req.URL.Query().Get("url")
	if url == "" {
		http.Error(rw, "Missing url parameter.", http.StatusBadRequest)
		return
	}
	code, err := qr.Encode(url, qr.L)
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	rw.Header().Set("Content-Type", "image/png")
	rw.Write(code.PNG())
}
Ejemplo n.º 18
0
func main() {
	v := flag.Bool("v", false, "show version")
	flag.Parse()

	if *v {
		fmt.Println("version:0.1.1.dev")
		os.Exit(0)
	}

	text := uuid.New()
	data, _ := qr.Encode(text, qr.H)
	content := data.PNG()
	fmt.Println(text)
	ioutil.WriteFile(text+".png", content, 0644)
}
Ejemplo n.º 19
0
func qenerate(text string) (png []byte, err error) {
	res := <-storage.Call("read", cacheNamepspace, text)
	if res.Err() == nil {
		err = res.Extract(&png)
		return
	}

	c, err := qr.Encode(text, qr.L)
	if err != nil {
		return
	}
	png = c.PNG()

	<-storage.Call("write", cacheNamepspace, text, string(png), []string{cacheTag})
	return
}
Ejemplo n.º 20
0
//func get_qr(t string) image.Image {
func get_qr(t string) string {
	var q *qr.Code
	var e error

	q, e = qr.Encode(t, qr.L)
	if e != nil {
		fmt.Println(e)
	}

	fmt.Println(t)
	fmt.Print("QR Code Size (Pixels) = ")
	fmt.Println(q.Size)
	q.Scale = *mult

	//	return q.Image()
	return string(q.PNG())
}
Ejemplo n.º 21
0
//Generates QR-Code based on Status URI and places in the images/qrcodes directory
func GenStatusQRCode(fwidURI string) {
	// Turns Out Go doesnt support Positive Lookbehind as it is
	//https://groups.google.com/d/msg/golang-nuts/7qgSDWPIh_E/OHTAm4wRZL0J
	//re := regexp.MustCompile(`(?<=\/status\/)([0-9a-f]+)`)
	//log.Println(re.FindStringSubmatch(fwidURI))
	fwUriSplit := strings.Split(fwidURI, "/")
	fwid := fwUriSplit[4]
	log.Println(fwUriSplit)
	log.Println(fwid)
	c, err := qr.Encode(fwidURI, qr.L)
	if err != nil {
		log.Println(err)
	} else {
		pngdat := c.PNG()
		s := []string{"static/images/qrcodes/", fwid, ".png"}
		ioutil.WriteFile(strings.Join(s, ""), pngdat, 0666)
	}
}
Ejemplo n.º 22
0
func GenerateNewSecretAndImage(issuer string) (string, string, error) {
	randomStr := randStr(6, "alphanum")
	secret := base32.StdEncoding.EncodeToString([]byte(randomStr))

	authLink := "otpauth://totp/" + issuer + "?secret=" + secret + "&issuer=" + issuer

	code, err := qr.Encode(authLink, qr.H)

	if err != nil {
		return "", "", err
	}

	imgByte := code.PNG()

	str := base64.StdEncoding.EncodeToString(imgByte)

	return secret, str, nil
}
Ejemplo n.º 23
0
func handleQRCodeRequest(c appengine.Context, w http.ResponseWriter, r *http.Request) {
	url := r.PostFormValue("url")
	if url == "" {
		writeError(w, errors.New("no url supplied"))
		return
	}

	account := getAccount(c)
	if account == nil {
		writeError(w, errors.New("no account"))
		return
	}

	QR, err := qr.Encode(url, qr.H)

	if err != nil {
		writeError(w, err)
		return
	}

	writeSuccess(w, simpleQRResponse{
		PNGData: QR.PNG(),
	})
}
Ejemplo n.º 24
0
func Qrcode(r *http.Request, w http.ResponseWriter) {
	text := r.FormValue("text")
	code, _ := qr.Encode(text, qr.M)
	w.Header().Set("Content-Type", "image/png")
	w.Write(code.PNG())
}
Ejemplo n.º 25
0
Archivo: qr.go Proyecto: erasche/go-otp
func QrAction() error {
	if qrPasswordFlag == "" {
		return errors.New("Must provide -password")
	}

	db, err := sql.Open("sqlite3", "auth.db")
	if err != nil {
		fmt.Println(err)
	}
	defer db.Close()

	p := fmt.Sprintf("PRAGMA key = '%s';", qrPasswordFlag)
	_, err = db.Exec(p)
	if err != nil {
		return err
	}

	e := "select account,issuer,password from users;"
	rows, err := db.Query(e)
	if err != nil {
		return err
	}
	defer rows.Close()

	for rows.Next() {
		var (
			account  string
			issuer   string
			password string
		)
		rows.Scan(&account, &issuer, &password)
		oath_url := fmt.Sprintf("otpauth://totp/%s:%s?secret=%s&issuer=%s", issuer, account, password, issuer)
		//otpauth://totp/Example:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Example
		code, err := qr.Encode(oath_url, qr.H)

		if err != nil {
			return err
		}

		imgByte := code.PNG()
		// convert byte to image for saving to file
		img, _, _ := image.Decode(bytes.NewReader(imgByte))

		//save the imgByte to file
		var filename = fmt.Sprintf("%s__%s.png", issuer, account)

		out, err := os.Create(filename)
		if err != nil {
			return err
		}

		err = png.Encode(out, img)
		if err != nil {
			return err
		}

		fmt.Printf("QR Code stored to %s\n", filename)
	}
	rows.Close()

	return nil
}
Ejemplo n.º 26
0
Archivo: 2fa.go Proyecto: yoshiotu/2fa
func main() {
	// Example secret from here:
	// https://github.com/google/google-authenticator/wiki/Key-Uri-Format
	secret := []byte{'H', 'e', 'l', 'l', 'o', '!', 0xDE, 0xAD, 0xBE, 0xEF}

	// Generate random secret instead of using the test value above.
	// secret := make([]byte, 6)
	// _, err := rand.Read(secret)
	// if err != nil {
	//	panic(err)
	// }

	secretBase32 := base32.StdEncoding.EncodeToString(secret)

	account := "*****@*****.**"

	URL, err := url.Parse("otpauth://totp")
	if err != nil {
		panic(err)
	}

	URL.Path += "/NameOfMyService:" + account
	params := url.Values{}
	params.Add("secret", secretBase32)
	params.Add("issuer", "NameOfMyService")

	URL.RawQuery = params.Encode()

	fmt.Printf("URL is %s\n", URL.String())

	code, err := qr.Encode(URL.String(), qr.Q)
	if err != nil {
		panic(err)
	}
	b := code.PNG()
	err = ioutil.WriteFile(qrFilename, b, 0600)
	if err != nil {
		panic(err)
	}

	fmt.Printf("QR code is in %s. Please scan it into Google Authenticator app.\n", qrFilename)

	var token string
	fmt.Printf("Please enter the token value: ")
	fmt.Scanln(&token)

	otpc := &dgoogauth.OTPConfig{
		Secret:      secretBase32,
		WindowSize:  3,
		HotpCounter: 0,
	}

	val, err := otpc.Authenticate(token)
	if err != nil {
		panic(err)
	}

	if val {
		fmt.Printf("Got true val\n")
	} else {
		fmt.Printf("Got false val\n")
	}
	return
}
Ejemplo n.º 27
0
func main() {

	level := flag.String("level", "m", "QR level: L/M/Q/H")

	flag.Parse()

	var qrLevel qr.Level

	switch *level {
	case "L", "l":
		qrLevel = qr.L
	case "M", "m":
		qrLevel = qr.M
	case "H", "h":
		qrLevel = qr.H
	case "Q", "q":
		qrLevel = qr.Q
	default:
		log.Fatal("unknown QR level:", *level)
	}

	data := flag.Arg(0)

	code, _ := qr.Encode(data, qrLevel)

	black := "\033[30;40m"
	white := "\033[30;47m"
	reset := "\033[0m"

	fmt.Print(reset)

	// two pixel border
	for i := 0; i < 2; i++ {
		fmt.Print(white + "    ")
		for x := 0; x < code.Size; x++ {
			fmt.Print("  ")
		}
		fmt.Println("    " + reset)
	}

	for x := 0; x < code.Size; x++ {
		fmt.Print(white + "    ") // two pixel border
		for y := 0; y < code.Size; y++ {
			if code.Black(x, y) {
				fmt.Print(black + "  ")
			} else {
				fmt.Print(white + "  ")
			}
		}
		fmt.Println(white + "    " + reset) // two pixel border
	}

	// two pixel border
	for i := 0; i < 2; i++ {
		fmt.Print(white + "    ")
		for x := 0; x < code.Size; x++ {
			fmt.Print("  ")
		}
		fmt.Println(white + "    " + reset)
	}
}
Ejemplo n.º 28
0
// GenerateQR generates a for the receiver *Request.
func (r *Request) GenerateQR() (*qr.Code, error) {
	// get config for this request
	c := r.Config
	if c == nil {
		c = DefaultConfig
	}

	var err error

	// uriBuf will contain the bytes that are to be encoded into the QR code
	uriBuf := &bytes.Buffer{}

	// write uri scheme
	_, err = uriBuf.WriteString(c.scheme())
	if err != nil {
		return nil, err
	}

	// write uri seperator colon
	err = uriBuf.WriteByte(':')
	if err != nil {
		return nil, err
	}

	// write receiving address
	_, err = uriBuf.WriteString(r.Address)
	if err != nil {
		return nil, err
	}

	// params contains optional parameters used in the URI
	var params = make(map[string]string)

	// add amount when not zero
	if r.Amount < 0 {
		return nil, ErrNegativeAmount
	}
	if r.Amount != 0 {
		params["amount"] = strconv.FormatFloat(r.Amount, 'f', -1, 64)
		if err != nil {
			return nil, err
		}
	}

	// add label when it is not empty
	if len(r.Label) != 0 {
		params["label"] = url.QueryEscape(r.Label)
	}

	// add message when it is not empty
	if len(r.Message) != 0 {
		params["message"] = url.QueryEscape(r.Message)
	}

	// add query escaped params (if any)
	if r.Params != nil {
		for key, value := range r.Params {
			params[url.QueryEscape(key)] = url.QueryEscape(value)
		}
	}

	// write all parameters to the uriBuf
	q := true
	for key, value := range params {
		// write '?' or '&' to uriBuf
		if q {
			q = false
			err = uriBuf.WriteByte('?')
			if err != nil {
				return nil, err
			}
		} else {
			err = uriBuf.WriteByte('&')
			if err != nil {
				return nil, err
			}
		}

		// write <key>=<value> to uriBuf
		_, err = uriBuf.WriteString(key)
		if err != nil {
			return nil, err
		}
		err = uriBuf.WriteByte('=')
		if err != nil {
			return nil, err
		}
		_, err = uriBuf.WriteString(value)
		if err != nil {
			return nil, err
		}
	}

	// create qr image
	code, err := qr.Encode(uriBuf.String(), qr.Level(c.Level))
	if err != nil {
		return nil, err
	}

	// all done
	return code, nil
}
Ejemplo n.º 29
0
// AsQR creates a qr instance containing the data stored in the QrElement
func (elem *QrElement) AsQR() (*qr.Code, error) {
	return qr.Encode(elem.AsString(), qrLevel)
}