|
| 1 | +package controller |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "net/http" |
| 6 | + |
| 7 | + "example.com/clean-arch/entity" |
| 8 | + "example.com/clean-arch/errors" |
| 9 | + "example.com/clean-arch/service" |
| 10 | +) |
| 11 | + |
| 12 | +type controller struct{} |
| 13 | + |
| 14 | +var ( |
| 15 | + postService service.PostService |
| 16 | +) |
| 17 | + |
| 18 | +type PostController interface { |
| 19 | + GetPosts(response http.ResponseWriter, request *http.Request) |
| 20 | + AddPost(response http.ResponseWriter, request *http.Request) |
| 21 | +} |
| 22 | + |
| 23 | +func NewPostController(service service.PostService) PostController { |
| 24 | + postService = service |
| 25 | + return &controller{} |
| 26 | +} |
| 27 | + |
| 28 | +func (*controller) GetPosts(response http.ResponseWriter, request *http.Request) { |
| 29 | + response.Header().Set("Content-Type", "application/json") |
| 30 | + posts, err := postService.FindAll() |
| 31 | + if err != nil { |
| 32 | + response.WriteHeader(http.StatusInternalServerError) |
| 33 | + json.NewEncoder(response).Encode(errors.ServiceError{Message: "Error getting the posts"}) |
| 34 | + } |
| 35 | + response.WriteHeader(http.StatusOK) |
| 36 | + json.NewEncoder(response).Encode(posts) |
| 37 | +} |
| 38 | + |
| 39 | +func (*controller) AddPost(response http.ResponseWriter, request *http.Request) { |
| 40 | + response.Header().Set("Content-Type", "application/json") |
| 41 | + var post entity.Post |
| 42 | + err := json.NewDecoder(request.Body).Decode(&post) |
| 43 | + if err != nil { |
| 44 | + response.WriteHeader(http.StatusInternalServerError) |
| 45 | + json.NewEncoder(response).Encode(errors.ServiceError{Message: "Error unmarshalling data"}) |
| 46 | + return |
| 47 | + } |
| 48 | + |
| 49 | + err = postService.Validate(&post) |
| 50 | + if err != nil { |
| 51 | + response.WriteHeader(http.StatusInternalServerError) |
| 52 | + json.NewEncoder(response).Encode(errors.ServiceError{Message: err.Error()}) |
| 53 | + return |
| 54 | + } |
| 55 | + |
| 56 | + result, err := postService.Create(&post) |
| 57 | + if err != nil { |
| 58 | + response.WriteHeader(http.StatusInternalServerError) |
| 59 | + json.NewEncoder(response).Encode(errors.ServiceError{Message: "Error saving the post"}) |
| 60 | + return |
| 61 | + } |
| 62 | + response.WriteHeader(http.StatusOK) |
| 63 | + json.NewEncoder(response).Encode(result) |
| 64 | +} |
0 commit comments