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 8 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"]
56 changes: 32 additions & 24 deletions cmd/main.go
Original file line number Diff line number Diff line change
@@ -1,52 +1,60 @@
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
logger *log.Logger
}

func main() {
var cfg config
flag.IntVar(&cfg.port, "port", 8080, "API server port")
flag.StringVar(&cfg.env, "env", "development", "Environment")
newPlaceRepo := repo.NewPLaceRepository()
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,
}
mux := http.NewServeMux()
mux.HandleFunc("/healthcheck", app.healthcheckHandler)
r := mux.NewRouter().PathPrefix("/api/v1").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("", healthcheckHandler).Methods(http.MethodGet)
placecheck := r.PathPrefix("/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 healthcheckHandler(w http.ResponseWriter, r *http.Request) {
_, 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=
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) {
places, err := h.uc.GetPlaces(r.Context())
if err != nil {
http.Error(w, "Не удалось получить список достопримечательностей", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(places)
if err != nil {
http.Error(w, "Не удалось преобразовать в json", http.StatusInternalServerError)
return
}
}
14 changes: 14 additions & 0 deletions internal/pkg/places/interfaces.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package places

import (
"TripAdvisor/internal/models"
"context"
)

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

type PlaceUsecase interface {
GetPlaces(ctx context.Context) ([]models.Place, error)
}
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": "Государственный музей Петергоф"
}
]

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

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

type PlaceRepository struct {
}

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

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

func (r *PlaceRepository) GetPlaces(ctx context.Context) ([]models.Place, error) {
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
}
23 changes: 23 additions & 0 deletions internal/pkg/places/usecase/usecase.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package usecase

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

type PlaceUsecaseImpl struct {
repo places.PlaceRepo
}

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

func (i *PlaceUsecaseImpl) GetPlaces(ctx context.Context) ([]models.Place, error) {
places, err := i.repo.GetPlaces(ctx)
if err != nil {
return nil, err
}
return places, nil
}
Empty file removed pkg/.gitkeep
Empty file.