38 lines
866 B
Go
38 lines
866 B
Go
package handlers
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
// readJSON reads and decodes JSON from request body
|
|
func readJSON(r *http.Request, v interface{}) error {
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read request body: %v", err)
|
|
}
|
|
|
|
if err := json.Unmarshal(body, v); err != nil {
|
|
return fmt.Errorf("invalid request format: %v", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// writeJSON writes JSON response with proper headers
|
|
func writeJSON(w http.ResponseWriter, v interface{}) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
json.NewEncoder(w).Encode(v)
|
|
}
|
|
|
|
// LogMiddleware logs all HTTP requests
|
|
func LogMiddleware(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
log.Printf("%s %s", r.Method, r.URL.Path)
|
|
next.ServeHTTP(w, r)
|
|
})
|
|
}
|