Last active
January 18, 2023 04:06
-
-
Save ezr/1fe17695122db3a35bf1307495c428ff to your computer and use it in GitHub Desktop.
Google Cloud function to create QR codes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Deployed with:
gcloud functions deploy QRMaker --runtime go119 --trigger-http --allow-unauthenticated