barcodes/web/routeGenerate.go

63 lines
1.5 KiB
Go

package web
import (
"encoding/json"
"fmt"
"image"
"image/png"
"net/http"
"git.fjla.uk/fred.boniface/barcodes/generation"
"git.fjla.uk/fred.boniface/barcodes/validation"
"github.com/boombuler/barcode"
)
func generateBarcode(w http.ResponseWriter, r *http.Request) {
var req BarcodeRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
parameters := generation.Parameters{
Format: generation.BarcodeType(req.BarcodeType),
ECCLevel: generation.ECCLevel(req.ECCLevel),
Content: req.Content,
}
validate := validation.Validate(req.Content, req.BarcodeType)
if !validate {
fmt.Println("Validation Failed")
http.Error(w, "Validation Failed", http.StatusBadRequest)
return
}
barcodeGen, err := generation.Generate(parameters)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if barcodeGen == nil {
fmt.Println("Generation failed, no barcode created")
http.Error(w, "Barcode Generation Failed", http.StatusInternalServerError)
return
}
barcodeGen, _ = barcode.Scale(barcodeGen, int(req.Width), int(req.Height))
image, isImage := barcodeGen.(image.Image)
if !isImage {
fmt.Println("Generation failed - no image")
http.Error(w, "Generated Barcode is not an image", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "image/png")
err = png.Encode(w, image)
if err != nil {
http.Error(w, "Error streaming barcode", http.StatusInternalServerError)
}
}