barcodes/web/generate.route.go

69 lines
1.7 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"
)
// Generates a barcode from the data and options provided in the request body
func generateBarcode(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Use a POST request for barcode generation", http.StatusMethodNotAllowed)
return
}
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(parameters)
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)
}
}