package main
import (
"context"
"encoding/json"
"fmt"
"io"
"github.com/fastly/compute-sdk-go/fsthttp"
"github.com/skip2/go-qrcode"
)
const BackendName = "origin_0"
type simpleQRCode struct {
Content string
Size int
}
func (code *simpleQRCode) Generate() ([]byte, error) {
qrCode, err := qrcode.Encode(code.Content, qrcode.Medium, code.Size)
if err != nil {
return nil, fmt.Errorf("could not generate a QR code: %v", err)
}
return qrCode, nil
}
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
if r.Method == "GET" && r.URL.Path == "/qr.png" {
url := r.URL.Query().Get("url")
if url != "" {
qrCode := simpleQRCode{Content: url, Size: 512}
codeData, err := qrCode.Generate()
if err != nil {
w.WriteHeader(400)
json.NewEncoder(w).Encode(
fmt.Sprintf("Could not generate QR code. %v", err),
)
return
}
w.Header().Set("Content-Type", "image/png")
w.Write(codeData)
}
}
resp, err := r.Send(ctx, BackendName)
if err != nil {
w.WriteHeader(fsthttp.StatusBadGateway)
fmt.Fprintln(w, err.Error())
return
}
w.Header().Reset(resp.Header)
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
})
}