|
| 1 | +package middleware |
| 2 | + |
| 3 | +import ( |
| 4 | + "Blogging-Platform-API/internal/model" |
| 5 | + "context" |
| 6 | + "encoding/json" |
| 7 | + "io" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | +) |
| 11 | + |
| 12 | +const PostKey = "post" |
| 13 | + |
| 14 | +func ValidatePostDTO(handler http.Handler) http.Handler { |
| 15 | + return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { |
| 16 | + requestBodyBytes, err := io.ReadAll(request.Body) |
| 17 | + if err != nil || len(requestBodyBytes) == 0 { |
| 18 | + log.Print("Error: Request Body cannot be empty") |
| 19 | + http.Error(writer, "Request Body cannot be empty", http.StatusBadRequest) |
| 20 | + return |
| 21 | + } |
| 22 | + var post model.PostDTO |
| 23 | + err = json.Unmarshal(requestBodyBytes, &post) |
| 24 | + if err != nil { |
| 25 | + log.Print("Error: Unmarshalling request Body") |
| 26 | + http.Error(writer, "Invalid request Body", http.StatusBadRequest) |
| 27 | + return |
| 28 | + } |
| 29 | + if post.Title == "" { |
| 30 | + log.Print("Error: Title field cannot be empty") |
| 31 | + http.Error(writer, "Title field cannot be empty", http.StatusUnprocessableEntity) |
| 32 | + return |
| 33 | + } |
| 34 | + if len(post.Title) > 255 { |
| 35 | + log.Print("Error: Invalid title length ", len(post.Title)) |
| 36 | + http.Error(writer, "Title field is too big", http.StatusUnprocessableEntity) |
| 37 | + return |
| 38 | + } |
| 39 | + if post.Content == "" { |
| 40 | + log.Print("Error: Content field is empty") |
| 41 | + http.Error(writer, "Content field is empty", http.StatusUnprocessableEntity) |
| 42 | + return |
| 43 | + } |
| 44 | + if len(post.Category) >= 30 { |
| 45 | + log.Print("Error: Category field is too big ", len(post.Category)) |
| 46 | + http.Error(writer, "Error: Category field is too big ", http.StatusUnprocessableEntity) |
| 47 | + return |
| 48 | + } |
| 49 | + ctx := context.WithValue(request.Context(), PostKey, post) |
| 50 | + handler.ServeHTTP(writer, request.WithContext(ctx)) |
| 51 | + }) |
| 52 | +} |
0 commit comments