forked from mattronix/escpos-go-labels
example web server
This commit is contained in:
parent
b75e892d2a
commit
1806a596ab
1 changed files with 60 additions and 0 deletions
60
main.go
Normal file
60
main.go
Normal file
|
@ -0,0 +1,60 @@
|
|||
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)
|
||||
}
|
||||
|
Loading…
Reference in a new issue