79 lines
1.8 KiB
Go
79 lines
1.8 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 StartServer() {
|
|
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Fprintf(w, "Barcodes")
|
|
})
|
|
|
|
http.HandleFunc("/generate", generateBarcode)
|
|
|
|
port := ":8500"
|
|
fmt.Printf("Server listening on port %s\n", port)
|
|
|
|
err := http.ListenAndServe(port, nil)
|
|
if err != nil {
|
|
fmt.Println("Error: ", err)
|
|
}
|
|
}
|
|
|
|
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, req.Width, 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)
|
|
}
|
|
}
|