2023-09-01 22:14:11 +01:00
|
|
|
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"
|
|
|
|
)
|
|
|
|
|
2023-09-02 22:05:46 +01:00
|
|
|
// Generates a barcode from the data and options provided in the request body
|
2023-09-01 22:14:11 +01:00
|
|
|
func generateBarcode(w http.ResponseWriter, r *http.Request) {
|
2023-09-02 22:05:46 +01:00
|
|
|
if r.Method != http.MethodPost {
|
|
|
|
http.Error(w, "Use a POST request for barcode generation", http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-09-01 22:14:11 +01:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2023-09-02 21:04:29 +01:00
|
|
|
validate := validation.Validate(parameters)
|
2023-09-01 22:14:11 +01:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|