udemy-go-microservices/logger-service/cmd/api/handlers.go

45 lines
754 B
Go
Raw Normal View History

2024-08-29 11:24:36 +00:00
package main
import (
2024-08-31 20:56:25 +00:00
"log"
2024-08-29 11:24:36 +00:00
"logger/data"
"net/http"
)
type JSONPayload struct {
Name string `json:"name"`
Data string `json:"data"`
}
func (app *Config) WriteLog(w http.ResponseWriter, r *http.Request) {
// read json into var
var requestPayload JSONPayload
2024-08-29 11:48:47 +00:00
err := app.readJSON(w, r, &requestPayload)
if err != nil {
app.errorJSON(w, err)
return
}
2024-08-31 20:56:25 +00:00
log.Println("requestpayload", requestPayload)
2024-08-29 11:24:36 +00:00
// insert data
event := data.LogEntry{
Name: requestPayload.Name,
Data: requestPayload.Data,
}
2024-08-31 20:56:25 +00:00
log.Println("event", event)
2024-08-29 11:48:47 +00:00
err = app.Models.LogEntry.Insert(event)
2024-08-29 11:24:36 +00:00
if err != nil {
app.errorJSON(w, err)
return
}
resp := jsonResponse{
Error: false,
Message: "logged",
}
app.writeJSON(w, http.StatusAccepted, resp)
}