Skip to content

Instantly share code, notes, and snippets.

@ezr
Last active January 18, 2023 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ezr/1fe17695122db3a35bf1307495c428ff to your computer and use it in GitHub Desktop.
Save ezr/1fe17695122db3a35bf1307495c428ff to your computer and use it in GitHub Desktop.
Google Cloud function to create QR codes
<!DOCTYPE html>
<html lang="en">
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title></title>
<style>
</style>
</head>
<body>
<h3>Make a QR Code:</h3>
<form action="/QRMaker" method="POST" id="form1">
<label for="data">Data:</label>
<input type="text" id="data" name="data"><br>
<input type="submit" value="Submit">
</form>
<br><br>
<h3>Your QR Code:</h3>
<img src="data:image/png;base64,{{.Result}}" alt="QR Code">
</body>
</html>
package qrmaker
import (
_ "embed"
"encoding/base64"
"html/template"
"log"
"net/http"
"github.com/GoogleCloudPlatform/functions-framework-go/functions"
qrcode "github.com/skip2/go-qrcode"
)
type Page struct {
Result string
}
//go:embed index.html
var index string
var (
tmpl, _ = template.New("index").Parse(index)
)
func init() {
functions.HTTP("QRMaker", QRMaker)
}
func QRMaker(w http.ResponseWriter, r *http.Request) {
var res = Page{}
if r.Method == "POST" {
r.ParseForm()
data := r.PostForm.Get("data")
if data == "" {
log.Println("no data supplied")
}
var png []byte
var pngSize = 256
if len(data) > 300 {
pngSize = 430
}
png, err := qrcode.Encode(data, qrcode.Medium, pngSize)
if err != nil {
log.Println(err)
}
pngB64 := base64.StdEncoding.EncodeToString(png)
res.Result = pngB64
}
err := tmpl.Execute(w, res)
if err != nil {
log.Println(err)
}
}
@ezr
Copy link
Author

ezr commented Jan 17, 2023

Deployed with: gcloud functions deploy QRMaker --runtime go119 --trigger-http --allow-unauthenticated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment