Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

place endpoint are added #3

Merged
merged 12 commits into from
Sep 29, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
.idea
.idea
go.mod
2024-2-Zdes-budet-nazvanie-UykwHnIE.crt
10 changes: 3 additions & 7 deletions build/main.Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,9 @@ COPY . /github.com/go-park-mail-ru/2024_2_ThereWillBeName
WORKDIR /github.com/go-park-mail-ru/2024_2_ThereWillBeName
RUN go mod download
RUN go clean --modcache
RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -o ./.bin ./cmd/main/main.go
RUN CGO_ENABLED=0 GOOS=linux go build -mod=readonly -o ./.bin ./cmd/main.go
FROM scratch AS runner
WORKDIR /build
COPY --from=builder /github.com/go-park-mail-ru/2024_2_ThereWillBeName/.bin .
COPY --from=builder /github.com/go-park-mail-ru/2024_2_ThereWillBeName/config config/
COPY --from=builder /usr/local/go/lib/time/zoneinfo.zip /
ENV TZ="Europe/Moscow"
ENV ZONEINFO=/zoneinfo.zip
EXPOSE 80 443 8080
ENTRYPOINT ["./.bin"]
EXPOSE 8080
ENTRYPOINT ["./.bin"]
52 changes: 35 additions & 17 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,52 +1,70 @@
package main

import (
"TripAdvisor/internal/models"
"TripAdvisor/internal/pkg/middleware"
"TripAdvisor/internal/pkg/places/delivery"
"TripAdvisor/internal/pkg/places/repo"
"TripAdvisor/internal/pkg/places/usecase"
"flag"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"os"
"time"
)

type config struct {
port int
env string
}
type application struct {
config config
config models.Config
logger *log.Logger
}
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved

func main() {
var cfg config
flag.IntVar(&cfg.port, "port", 8080, "API server port")
flag.StringVar(&cfg.env, "env", "development", "Environment")

timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
newPlaceRepo := repo.NewRepository()
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
placeUsecase := usecase.NewPlaceUsecase(newPlaceRepo)
handler := delivery.NewPlacesHandler(placeUsecase)

var cfg models.Config
flag.IntVar(&cfg.Port, "port", 8080, "API server port")
flag.StringVar(&cfg.Env, "env", "development", "Environment")
flag.Parse()
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved

logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
app := &application{
config: cfg,
logger: logger,
config: cfg,
}
mux := http.NewServeMux()
mux.HandleFunc("/healthcheck", app.healthcheckHandler)
r := mux.NewRouter().PathPrefix("/api").Subrouter()
r.Use(middleware.CORSMiddleware)
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
r.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "Not Found", http.StatusNotFound)
})
healthcheck := r.PathPrefix("/healthcheck").Subrouter()
healthcheck.HandleFunc("", app.HealthcheckHandler).Methods(http.MethodGet)
placecheck := r.PathPrefix("/v1/places").Subrouter()
placecheck.HandleFunc("", handler.GetPlaceHandler).Methods(http.MethodGet)
srv := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.port),
Handler: mux,
Addr: fmt.Sprintf(":%d", cfg.Port),
Handler: r,
IdleTimeout: time.Minute,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
logger.Printf("starting %s server on %s", cfg.env, srv.Addr)

logger.Printf("starting %s server on %s", cfg.Env, srv.Addr)
err := srv.ListenAndServe()
if err != nil {
logger.Fatal(err)
fmt.Errorf("Failed to start server: %v", err)
os.Exit(1)
}
}

func (app *application) healthcheckHandler(w http.ResponseWriter, r *http.Request) {
func (app *application) HealthcheckHandler(w http.ResponseWriter, r *http.Request) {
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
_, err := fmt.Fprintf(w, "STATUS: OK")
if err != nil {
fmt.Printf("ERROR: healthcheckHandler: %s\n", err)
http.Error(w, "", http.StatusBadRequest)
fmt.Errorf("ERROR: healthcheckHandler: %s\n", err)
}
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
module TripAdvisor
go 1.23.0
require github.com/gorilla/mux v1.8.1
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
Binary file added images/image1.png
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/image2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/image3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/image4.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/image5.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added images/image6.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Empty file removed internal/.gitkeep
Empty file.
6 changes: 6 additions & 0 deletions internal/models/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package models

type Config struct {
Port int
Env string
}
7 changes: 7 additions & 0 deletions internal/models/place.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package models

type Place struct {
ID int `json:"id"`
Name string `json:"name""`
Image string `json:"image"`
}
16 changes: 16 additions & 0 deletions internal/pkg/middleware/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package middleware

import "net/http"

func CORSMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Methods", "POST,PUT,DELETE,GET")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот это плохо. Суть CORS в том, что бэкенд отдает этим заголовком информацию браузеру, с каких сайтов (Origin) пропускать запросы на бэк. А мы таким образом будем позволять браузеру отправлять запросы на бэк с любого сайта. В общем смотри инфу про cors (например тут).

timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
if r.Method == http.MethodOptions {
return
}
next.ServeHTTP(w, r)
})
}
29 changes: 29 additions & 0 deletions internal/pkg/places/delivery/http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package delivery

import (
"TripAdvisor/internal/pkg/places"
"encoding/json"
"net/http"
)

type PlacesHandler struct {
uc places.PlaceUsecase
}

func NewPlacesHandler(uc places.PlaceUsecase) *PlacesHandler {
return &PlacesHandler{uc}
}

func (h *PlacesHandler) GetPlaceHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
places, err := h.uc.GetPlaces()
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
http.Error(w, "Не удалось получить список достопримечательностей", http.StatusInternalServerError)
return
}
err = json.NewEncoder(w).Encode(places)
if err != nil {
http.Error(w, "Не удалось преобразовать в json", http.StatusInternalServerError)
return
}
}
13 changes: 13 additions & 0 deletions internal/pkg/places/interfaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package places

import (
"TripAdvisor/internal/models"
)

type PlaceRepo interface {
GetPlaces() ([]models.Place, error)
}

type PlaceUsecase interface {
GetPlaces() ([]models.Place, error)
}
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
33 changes: 33 additions & 0 deletions internal/pkg/places/repo/places.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
[
{
"id": 0,
"image": "/images/image1.png",
"name": "Московский Кремль"
},
{
"id": 1,
"image": "/images/image2.png",
"name": "Красная Площадь"
},
{
"id": 2,
"image": "/images/image3.png",
"name": "Храм Василия Блаженного"
},
{
"id": 3,
"image": "/images/image4.png",
"name": "Большой театр"
},
{
"id": 4,
"image": "/images/image5.png",
"name": "Государственная Третьяковская галерея"
},
{
"id": 5,
"image": "/images/image6.png",
"name": "Государственный музей Петергоф"
}
]

30 changes: 30 additions & 0 deletions internal/pkg/places/repo/repo.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package repo

import (
"TripAdvisor/internal/models"
_ "embed"
"encoding/json"
"log"
)

type PlaceRepository struct {
}

func NewRepository() *PlaceRepository {
return &PlaceRepository{}
}

//go:embed places.json
var jsonFileData []byte

func (r *PlaceRepository) GetPlaces() ([]models.Place, error) {
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
images := make([]models.Place, 0)
log.Println("1")
err := json.Unmarshal(jsonFileData, &images)
if err != nil {
log.Println(err)
return nil, err
}
log.Println(images)
return images, nil
}
22 changes: 22 additions & 0 deletions internal/pkg/places/usecase/usecase.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package usecase

import (
"TripAdvisor/internal/models"
"TripAdvisor/internal/pkg/places"
)

type PlaceUsecaseImpl struct {
repo places.PlaceRepo
}

func NewPlaceUsecase(repo places.PlaceRepo) *PlaceUsecaseImpl {
return &PlaceUsecaseImpl{repo: repo}
}

func (i *PlaceUsecaseImpl) GetPlaces() ([]models.Place, error) {
places, err := i.repo.GetPlaces()
timurIsaevIY marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
return places, nil
}
Empty file removed pkg/.gitkeep
Empty file.