當前位置: 首頁>>代碼示例>>Golang>>正文


Golang qr.Encode函數代碼示例

本文整理匯總了Golang中code/google/com/p/rsc/qr.Encode函數的典型用法代碼示例。如果您正苦於以下問題:Golang Encode函數的具體用法?Golang Encode怎麽用?Golang Encode使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Encode函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: BarcodeImage

// 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
}
開發者ID:nzlov,項目名稱:totp,代碼行數:31,代碼來源:totp.go

示例2: registerMFA

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",
	})
}
開發者ID:leifmadsen,項目名稱:gobot,代碼行數:29,代碼來源:mfa.go

示例3: QRHandler

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)
}
開發者ID:sedalu,項目名稱:sqrl,代碼行數:33,代碼來源:server.go

示例4: main

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)
	}
}
開發者ID:minoritea,項目名稱:qrgen,代碼行數:25,代碼來源:main.go

示例5: GenTicket

// 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"])
}
開發者ID:capnfuzz,項目名稱:qrtickets,代碼行數:32,代碼來源:tickets.go

示例6: createQR

// 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
}
開發者ID:szwork2013,項目名稱:gopixelrelay,代碼行數:33,代碼來源:qr.go

示例7: qrHandler

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())
}
開發者ID:postfix,項目名稱:qrifidb,代碼行數:34,代碼來源:main.go

示例8: QR

// 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
}
開發者ID:carriercomm,項目名稱:api-1,代碼行數:10,代碼來源:hotp.go

示例9: generateQr

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()
}
開發者ID:StormGoth,項目名稱:GenerateQR,代碼行數:56,代碼來源:GenerateQR.go

示例10: Generate

// 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
}
開發者ID:GeertJohan,項目名稱:go.qrt,代碼行數:56,代碼來源:qrt.go

示例11: encode

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)
	}

}
開發者ID:Ticketbud,項目名稱:qrservice,代碼行數:12,代碼來源:web.go

示例12: AddTicket

// 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)
}
開發者ID:capnfuzz,項目名稱:qrtickets,代碼行數:53,代碼來源:tickets.go

示例13: viewHandler

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);
}
開發者ID:redage,項目名稱:apps,代碼行數:13,代碼來源:test.go

示例14: Encode

// 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
}
開發者ID:mark-adams,項目名稱:client,代碼行數:15,代碼來源:qrcode.go

示例15: getNewUserSession_API

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)
}
開發者ID:Tok3n,項目名稱:OpenTok3n,代碼行數:38,代碼來源:apiv1.go


注:本文中的code/google/com/p/rsc/qr.Encode函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。