forked from mattronix/escpos-go-labels
61 lines
1.4 KiB
Go
61 lines
1.4 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
"log"
|
||
|
"os"
|
||
|
)
|
||
|
|
||
|
// RequestData represents the JSON request body structure
|
||
|
type RequestData struct {
|
||
|
Date string `json:"date"`
|
||
|
Nickname string `json:"nickname"`
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
// Set the output to unbuffered
|
||
|
log.SetOutput(os.Stdout)
|
||
|
|
||
|
http.HandleFunc("/print/dnh-label", func(w http.ResponseWriter, r *http.Request) {
|
||
|
// Only handle POST requests
|
||
|
if r.Method != http.MethodPost {
|
||
|
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Parse JSON request body
|
||
|
var requestData RequestData
|
||
|
decoder := json.NewDecoder(r.Body)
|
||
|
if err := decoder.Decode(&requestData); err != nil {
|
||
|
http.Error(w, "Invalid JSON request body", http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Validate the date format
|
||
|
_, err := time.Parse("2006-01-02", requestData.Date)
|
||
|
if err != nil {
|
||
|
http.Error(w, "Invalid date format. Please use yyyy-mm-dd", http.StatusBadRequest)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
// Process the request
|
||
|
response := fmt.Sprintf("Received Date: %s, Nickname: %s", requestData.Date, requestData.Nickname)
|
||
|
|
||
|
// Send a JSON response
|
||
|
w.Header().Set("Content-Type", "application/json")
|
||
|
w.WriteHeader(http.StatusOK)
|
||
|
json.NewEncoder(w).Encode(map[string]string{"message": response})
|
||
|
|
||
|
// Force immediate output to the console
|
||
|
log.Println(response)
|
||
|
})
|
||
|
|
||
|
// Start the server
|
||
|
fmt.Println("Server is running on :8080")
|
||
|
http.ListenAndServe(":8080", nil)
|
||
|
}
|
||
|
|