forked from Alexey/DAS_2024_1
Compare commits
1 Commits
zhimolostn
...
dozorova_a
| Author | SHA1 | Date | |
|---|---|---|---|
| 080625d270 |
2
bazunov_andrew_lab_1/.gitignore
vendored
2
bazunov_andrew_lab_1/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
ollama
|
||||
./ollama
|
||||
@@ -1,33 +0,0 @@
|
||||
# Распределенные вычисления и приложения Л1
|
||||
## _Автор Базунов Андрей Игревич ПИбд-42_
|
||||
|
||||
В качестве сервисов были выбраны:
|
||||
- 1.Ollama (_Сервис для использования LLMs моделей_)
|
||||
- 2.Open Web Ui (_Сервис для удобного общения с моделью из сервиса Ollama_)
|
||||
- 3.Gitea (_Гит сервис_)
|
||||
|
||||
# Docker
|
||||
|
||||
>Перед исполнением вполняем установку docker и проверяем версию
|
||||
|
||||
```sh
|
||||
docker-compose --version
|
||||
```
|
||||
|
||||
>Далее производим настройку файла docker-compose.yaml и запускаем контейнер
|
||||
|
||||
```sh
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
>Для завершения работы контейнера используем команду
|
||||
```sh
|
||||
docker-compose down
|
||||
```
|
||||
---
|
||||
> Замечание: после запуска контейнера, необходимо перейти в контейнер **ollamа** и выполнить установку модели [gemma2](https://ollama.com/library/gemma2:2b)
|
||||
> ```sh
|
||||
> docker-compose exec ollama ollama run ollama run gemma2:2b
|
||||
> ```
|
||||
---
|
||||
Далее можно использовать веб сервис Open Web Ui по адресу **localhost:8080** для общения с моделью и Gitea по адресу **localhost:3000** - [демонстрация работы](https://vk.com/video/@viltskaa?z=video236673313_456239574%2Fpl_236673313_-2)
|
||||
@@ -1,61 +0,0 @@
|
||||
services:
|
||||
gitea: # Имя сервиса
|
||||
image: gitea/gitea:latest # Имя образа
|
||||
container_name: gitea # Имя контейнера, может быть произовольным
|
||||
ports:
|
||||
- "3000:3000" # Проброс порта Gitea на хост
|
||||
volumes: # хранилище
|
||||
- data:/data
|
||||
environment: # переменные окружения
|
||||
USER_UID: 1000
|
||||
USER_GID: 1000
|
||||
|
||||
ollama:
|
||||
image: ollama/ollama:latest
|
||||
container_name: ollama
|
||||
restart: always
|
||||
ports:
|
||||
- 7869:11434
|
||||
pull_policy: always
|
||||
tty: true
|
||||
volumes:
|
||||
- .:/code
|
||||
- ./ollama/ollama:/root/.ollama # Директория для данных Ollama
|
||||
environment:
|
||||
- OLLAMA_KEEP_ALIVE=24h
|
||||
- OLLAMA_HOST=0.0.0.0 # Указываем хост для API Ollama
|
||||
networks:
|
||||
- ollama-docker
|
||||
command: ["serve"] # Запускаем Ollama в режиме сервера
|
||||
|
||||
ollama-webui:
|
||||
image: ghcr.io/open-webui/open-webui:main # Образ Open Web UI
|
||||
container_name: ollama-webui
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- ./ollama/ollama-webui:/app/backend/data
|
||||
ports:
|
||||
- 8080:8080 # Порт для веб-интерфейса
|
||||
environment: # https://docs.openwebui.com/getting-started/env-configuration#default_models
|
||||
- OLLAMA_BASE_URLS=http://host.docker.internal:7869
|
||||
- ENV=dev
|
||||
- WEBUI_AUTH=False
|
||||
- WEBUI_NAME=Viltskaa AI
|
||||
- WEBUI_URL=http://localhost:8080
|
||||
- WEBUI_SECRET_KEY=t0p-s3cr3t
|
||||
depends_on:
|
||||
- ollama
|
||||
extra_hosts:
|
||||
- host.docker.internal:host-gateway
|
||||
networks:
|
||||
- ollama-docker
|
||||
|
||||
networks:
|
||||
ollama-docker:
|
||||
external: false
|
||||
|
||||
volumes:
|
||||
ollama:
|
||||
driver: local
|
||||
data:
|
||||
driver: local
|
||||
7
dozorova_alena_lab_3/.gitignore
vendored
Normal file
7
dozorova_alena_lab_3/.gitignore
vendored
Normal file
@@ -0,0 +1,7 @@
|
||||
|
||||
/dozorova_alena_lab_3/PostService/.vs
|
||||
/dozorova_alena_lab_3/PostService/bin
|
||||
/dozorova_alena_lab_3/PostService/obj
|
||||
/dozorova_alena_lab_3/WorkerService/.vs
|
||||
/dozorova_alena_lab_3/WorkerService/bin
|
||||
/dozorova_alena_lab_3/WorkerService/obj
|
||||
30
dozorova_alena_lab_3/PostService/.dockerignore
Normal file
30
dozorova_alena_lab_3/PostService/.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
@@ -0,0 +1,94 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace PostService.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class HomeController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<HomeController> _logger;
|
||||
|
||||
public static List<Post> list = new List<Post>()
|
||||
{
|
||||
new Post()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = "Default"
|
||||
}
|
||||
};
|
||||
public HomeController(ILogger<HomeController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
[HttpGet("get")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
return list == null || list.Count == 0 ? NotFound() : Ok(list);
|
||||
}
|
||||
|
||||
[HttpGet("get/{Id}")]
|
||||
public IActionResult Get([FromRoute] Guid Id)
|
||||
{
|
||||
var obj = list.Where(l => l.Id == Id).FirstOrDefault();
|
||||
return obj == null ? NotFound() : Ok(obj);
|
||||
}
|
||||
|
||||
[HttpPost("create")]
|
||||
public IActionResult Create([FromBody] CreateUpdatePost data)
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = new Post()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Name = data.Name,
|
||||
};
|
||||
|
||||
list.Add(model);
|
||||
|
||||
var modelForResult = new CreateUpdatePost
|
||||
{
|
||||
Name = model.Name
|
||||
};
|
||||
|
||||
return Ok(modelForResult);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("update/{Id}")]
|
||||
public IActionResult Update([FromRoute] Guid Id,
|
||||
[FromBody] CreateUpdatePost data)
|
||||
{
|
||||
var oldModel = list.Where(l => l.Id == Id).Select(l => list.IndexOf(l)).FirstOrDefault();
|
||||
if (oldModel != null)
|
||||
{
|
||||
list[oldModel].Name = data.Name;
|
||||
|
||||
var modelForResult = new CreateUpdatePost {
|
||||
Name = data.Name,
|
||||
};
|
||||
|
||||
return Ok(modelForResult);
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
|
||||
[HttpDelete("delete/{Id}")]
|
||||
public IActionResult Delete([FromRoute] Guid Id)
|
||||
{
|
||||
var model = list.Where(l => l.Id != Id).FirstOrDefault();
|
||||
|
||||
if (model != null) {
|
||||
list.Remove(model);
|
||||
return Ok();
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
}
|
||||
}
|
||||
24
dozorova_alena_lab_3/PostService/Dockerfile
Normal file
24
dozorova_alena_lab_3/PostService/Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
||||
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
EXPOSE 443
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["PostService.csproj", "."]
|
||||
RUN dotnet restore "./PostService.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/."
|
||||
RUN dotnet build "./PostService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./PostService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "PostService.dll"]
|
||||
16
dozorova_alena_lab_3/PostService/Entities.cs
Normal file
16
dozorova_alena_lab_3/PostService/Entities.cs
Normal file
@@ -0,0 +1,16 @@
|
||||
namespace PostService
|
||||
{
|
||||
public class Post
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
public class PostDTO : Post { }
|
||||
|
||||
public class CreateUpdatePost
|
||||
{
|
||||
public string Name { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
18
dozorova_alena_lab_3/PostService/PostService.csproj
Normal file
18
dozorova_alena_lab_3/PostService/PostService.csproj
Normal file
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>1a8ae13d-1a3e-4308-955e-4fbf68b758c9</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DockerfileContext>.</DockerfileContext>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
9
dozorova_alena_lab_3/PostService/PostService.csproj.user
Normal file
9
dozorova_alena_lab_3/PostService/PostService.csproj.user
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>PostService</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
25
dozorova_alena_lab_3/PostService/PostService.sln
Normal file
25
dozorova_alena_lab_3/PostService/PostService.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.35004.147
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PostService", "PostService.csproj", "{EB304D56-A05F-41BC-9523-B5FEB658BCEE}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{EB304D56-A05F-41BC-9523-B5FEB658BCEE}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {6625EB51-D403-4C57-A7C2-AA01C90AB472}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
31
dozorova_alena_lab_3/PostService/Program.cs
Normal file
31
dozorova_alena_lab_3/PostService/Program.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
using Microsoft.OpenApi.Models;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseSwagger(c =>
|
||||
{
|
||||
|
||||
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
|
||||
{
|
||||
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/postservice" } };
|
||||
});
|
||||
});
|
||||
app.UseSwaggerUI();
|
||||
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"profiles": {
|
||||
"PostService": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7293;http://localhost:5139"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_URLS": "https://+:443;http://+:80"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:36974",
|
||||
"sslPort": 44370
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
dozorova_alena_lab_3/PostService/appsettings.json
Normal file
9
dozorova_alena_lab_3/PostService/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
30
dozorova_alena_lab_3/WorkerService/.dockerignore
Normal file
30
dozorova_alena_lab_3/WorkerService/.dockerignore
Normal file
@@ -0,0 +1,30 @@
|
||||
**/.classpath
|
||||
**/.dockerignore
|
||||
**/.env
|
||||
**/.git
|
||||
**/.gitignore
|
||||
**/.project
|
||||
**/.settings
|
||||
**/.toolstarget
|
||||
**/.vs
|
||||
**/.vscode
|
||||
**/*.*proj.user
|
||||
**/*.dbmdl
|
||||
**/*.jfm
|
||||
**/azds.yaml
|
||||
**/bin
|
||||
**/charts
|
||||
**/docker-compose*
|
||||
**/Dockerfile*
|
||||
**/node_modules
|
||||
**/npm-debug.log
|
||||
**/obj
|
||||
**/secrets.dev.yaml
|
||||
**/values.dev.yaml
|
||||
LICENSE
|
||||
README.md
|
||||
!**/.gitignore
|
||||
!.git/HEAD
|
||||
!.git/config
|
||||
!.git/packed-refs
|
||||
!.git/refs/heads/**
|
||||
112
dozorova_alena_lab_3/WorkerService/Controllers/HomeController.cs
Normal file
112
dozorova_alena_lab_3/WorkerService/Controllers/HomeController.cs
Normal file
@@ -0,0 +1,112 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using RestSharp;
|
||||
|
||||
namespace WorkerService.Controllers
|
||||
{
|
||||
[ApiController]
|
||||
[Route("[controller]")]
|
||||
public class HomeController : ControllerBase
|
||||
{
|
||||
private readonly ILogger<HomeController> _logger;
|
||||
private readonly RestClient _restClient;
|
||||
|
||||
public static List<WorkerEntity> list = new List<WorkerEntity>();
|
||||
public HomeController(ILogger<HomeController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
_restClient = new RestClient("http://nginx/postservice/Home");
|
||||
}
|
||||
|
||||
[HttpGet("get")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
if (list == null || list.Count == 0)
|
||||
{
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
var result = list.Select(l => new GetEntity
|
||||
{
|
||||
Id = l.Id,
|
||||
FIO = l.FIO,
|
||||
PostId = l.PostId,
|
||||
});
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
|
||||
[HttpGet("get/{Id}")]
|
||||
public IActionResult Get([FromRoute] Guid Id)
|
||||
{
|
||||
var obj = list.Where(l => l.Id == Id);
|
||||
return obj == null ? NotFound() : Ok(obj);
|
||||
}
|
||||
|
||||
[HttpPost("create")]
|
||||
public async Task<IActionResult> CreateAsync([FromBody] CreateUpdateWorker data)
|
||||
{
|
||||
try
|
||||
{
|
||||
var model = new WorkerEntity()
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
FIO = data.FIO,
|
||||
PostId = data.PostId,
|
||||
};
|
||||
|
||||
var restRequest = new RestRequest($"/get/{data.PostId}", Method.Get);
|
||||
var responce = await _restClient.ExecuteAsync<PostEntity>(restRequest);
|
||||
|
||||
if (!responce.IsSuccessful)
|
||||
{
|
||||
return BadRequest(responce);
|
||||
}
|
||||
|
||||
model.Post = responce.Data;
|
||||
|
||||
list.Add(model);
|
||||
|
||||
return Ok(model);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return BadRequest(ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut("update/{Id}")]
|
||||
public IActionResult Update([FromRoute] Guid Id,
|
||||
[FromBody] CreateUpdateWorker data)
|
||||
{
|
||||
var oldModel = list.Where(l => l.Id == Id).Select(l => list.IndexOf(l)).FirstOrDefault();
|
||||
if (oldModel != null)
|
||||
{
|
||||
list[oldModel].FIO = data.FIO;
|
||||
list[oldModel].PostId = data.PostId;
|
||||
|
||||
var modelForResult = new CreateUpdateWorker
|
||||
{
|
||||
FIO = data.FIO,
|
||||
PostId = data.PostId,
|
||||
};
|
||||
|
||||
return Ok(modelForResult);
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
|
||||
[HttpDelete("delete/{Id}")]
|
||||
public IActionResult Delete([FromRoute] Guid Id)
|
||||
{
|
||||
var model = list.Where(l => l.Id != Id).FirstOrDefault();
|
||||
|
||||
if (model != null)
|
||||
{
|
||||
list.Remove(model);
|
||||
return Ok();
|
||||
}
|
||||
else return NotFound();
|
||||
}
|
||||
}
|
||||
}
|
||||
24
dozorova_alena_lab_3/WorkerService/Dockerfile
Normal file
24
dozorova_alena_lab_3/WorkerService/Dockerfile
Normal file
@@ -0,0 +1,24 @@
|
||||
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
EXPOSE 443
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
WORKDIR /src
|
||||
COPY ["WorkerService.csproj", "."]
|
||||
RUN dotnet restore "./WorkerService.csproj"
|
||||
COPY . .
|
||||
WORKDIR "/src/."
|
||||
RUN dotnet build "./WorkerService.csproj" -c $BUILD_CONFIGURATION -o /app/build
|
||||
|
||||
FROM build AS publish
|
||||
ARG BUILD_CONFIGURATION=Release
|
||||
RUN dotnet publish "./WorkerService.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
|
||||
|
||||
FROM base AS final
|
||||
WORKDIR /app
|
||||
COPY --from=publish /app/publish .
|
||||
ENTRYPOINT ["dotnet", "WorkerService.dll"]
|
||||
32
dozorova_alena_lab_3/WorkerService/Entities.cs
Normal file
32
dozorova_alena_lab_3/WorkerService/Entities.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
namespace WorkerService
|
||||
{
|
||||
public class WorkerEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string FIO { get; set; }
|
||||
|
||||
public Guid PostId { get; set; }
|
||||
public PostEntity Post { get; set; }
|
||||
}
|
||||
|
||||
public class PostEntity
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
public string name { get; set; }
|
||||
}
|
||||
|
||||
public class CreateUpdateWorker
|
||||
{
|
||||
public string FIO { get; set; }
|
||||
|
||||
public Guid PostId { get; set; }
|
||||
}
|
||||
|
||||
public class GetEntity
|
||||
{
|
||||
public Guid Id { get; set; }
|
||||
public string FIO { get; set; }
|
||||
|
||||
public Guid PostId { get; set; }
|
||||
}
|
||||
}
|
||||
32
dozorova_alena_lab_3/WorkerService/Program.cs
Normal file
32
dozorova_alena_lab_3/WorkerService/Program.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Microsoft.OpenApi.Models;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// Add services to the container.
|
||||
|
||||
builder.Services.AddControllers();
|
||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
app.UseSwagger(c =>
|
||||
{
|
||||
|
||||
c.PreSerializeFilters.Add((swaggerDoc, httpReq) =>
|
||||
{
|
||||
swaggerDoc.Servers = new List<OpenApiServer> { new OpenApiServer { Url = $"{httpReq.Scheme}://{httpReq.Host.Value}/workerservice" } };
|
||||
});
|
||||
});
|
||||
|
||||
app.UseSwaggerUI();
|
||||
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"profiles": {
|
||||
"WorkerService": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
},
|
||||
"dotnetRunMessages": true,
|
||||
"applicationUrl": "https://localhost:7144;http://localhost:5220"
|
||||
},
|
||||
"IIS Express": {
|
||||
"commandName": "IISExpress",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Container (Dockerfile)": {
|
||||
"commandName": "Docker",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_URLS": "https://+:443;http://+:80"
|
||||
},
|
||||
"publishAllPorts": true,
|
||||
"useSSL": true
|
||||
}
|
||||
},
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"iisSettings": {
|
||||
"windowsAuthentication": false,
|
||||
"anonymousAuthentication": true,
|
||||
"iisExpress": {
|
||||
"applicationUrl": "http://localhost:55850",
|
||||
"sslPort": 44303
|
||||
}
|
||||
}
|
||||
}
|
||||
18
dozorova_alena_lab_3/WorkerService/WorkerService.csproj
Normal file
18
dozorova_alena_lab_3/WorkerService/WorkerService.csproj
Normal file
@@ -0,0 +1,18 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>3228803c-add9-46fb-b949-9e2a2e89056a</UserSecretsId>
|
||||
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
|
||||
<DockerfileContext>.</DockerfileContext>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.20.1" />
|
||||
<PackageReference Include="RestSharp" Version="112.0.0" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>WorkerService</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
25
dozorova_alena_lab_3/WorkerService/WorkerService.sln
Normal file
25
dozorova_alena_lab_3/WorkerService/WorkerService.sln
Normal file
@@ -0,0 +1,25 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.10.35004.147
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WorkerService", "WorkerService.csproj", "{A9DF2332-E571-49AD-805A-D61B23C40D5F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A9DF2332-E571-49AD-805A-D61B23C40D5F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {B515427C-329A-4B73-B82C-45D929A6EA75}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
9
dozorova_alena_lab_3/WorkerService/appsettings.json
Normal file
9
dozorova_alena_lab_3/WorkerService/appsettings.json
Normal file
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
21
dozorova_alena_lab_3/docker-compose.yml
Normal file
21
dozorova_alena_lab_3/docker-compose.yml
Normal file
@@ -0,0 +1,21 @@
|
||||
services:
|
||||
nginx:
|
||||
image: nginx
|
||||
depends_on:
|
||||
- postservice
|
||||
- workerservice
|
||||
volumes:
|
||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf
|
||||
ports:
|
||||
- 80:80
|
||||
|
||||
postservice:
|
||||
build: .\PostService
|
||||
ports:
|
||||
- 81:8080
|
||||
workerservice:
|
||||
build: .\WorkerService
|
||||
ports:
|
||||
- 82:8080
|
||||
depends_on:
|
||||
- postservice
|
||||
21
dozorova_alena_lab_3/nginx/nginx.conf
Normal file
21
dozorova_alena_lab_3/nginx/nginx.conf
Normal file
@@ -0,0 +1,21 @@
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name localhost;
|
||||
|
||||
location /postservice/ {
|
||||
proxy_pass http://postservice:80/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Prefix /admin;
|
||||
}
|
||||
|
||||
location /workerservice/ {
|
||||
proxy_pass http://workerservice:80/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Forwarded-Prefix /admin;
|
||||
}
|
||||
}
|
||||
16
dozorova_alena_lab_3/readme.md
Normal file
16
dozorova_alena_lab_3/readme.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Лабораторная работа 3
|
||||
В работе представлен пример синхронного обмена сообщениями между сервисами и их взаимодейсвием с внешним миром.
|
||||
## Описание
|
||||
Были взяты две сущности: работник и должность. Первый сервис позволяет манипулировать списком должностей, второй - списком работников, у каждого из которых может быть одна должность. У одной должности может быть много работников.
|
||||
Реализована система была с помощью web-api на c# с хранением данных в оперативной памяти.
|
||||
В качестве интерфейса используется Swagger, который можно использовать для отправки запросов.
|
||||
## Запуск
|
||||
Для запуска лабораторной работы необходимо иметь запущенный Docker.
|
||||
Необходимо перейти в папку, где располагается данный файл. Далее открыть терминал и ввести команду:
|
||||
```
|
||||
docker compose up -d --build
|
||||
```
|
||||
Важно, чтобы в этот момент на компьютере был свободен порт 80.
|
||||
В результате, после сборки вся система запустится и Swagger-ы будут доступны по путям http://localhost/postservice/swagger и http://localhost/workerservice/swagger
|
||||
## Видеодемонстрация
|
||||
Видеодемонстрация результата лабораторной работы представлена по [адресу](https://drive.google.com/file/d/1rg2xnXM-jPDfFJWxNIitq0I8kXj9Pr3-/view?usp=sharing)
|
||||
2
tsukanova_irina_lab_2/.gitignore
vendored
2
tsukanova_irina_lab_2/.gitignore
vendored
@@ -1,2 +0,0 @@
|
||||
/.venv
|
||||
/.idea
|
||||
@@ -1,16 +0,0 @@
|
||||
# Цуканова Ирина ПИбд-32
|
||||
# Лабораторная работа №2 - Разработка простейшего распределённого приложения
|
||||
|
||||
### Язык разработки приложений: Python
|
||||
|
||||
## Выбранные варианты
|
||||
- Для программы 1: Ищет в каталоге ```/var/data``` самый большой по объёму файл и перекладывает его в ```/var/result/data.txt```.
|
||||
- Для программы 2: Сохраняет произведение первого и последнего числа из файла ```/var/result/data.txt``` в ```/var/result/result.txt```.
|
||||
|
||||
## Описание:
|
||||
Каждая программа лежит в своей папке, первая в worker-1, вторая в worker-2.
|
||||
В этих же папках лежат Dockerfile'ы с инструкциями по сборке. В них присутствуют комментарии для значимых строк.
|
||||
Монтированные папки ```data``` для ```/var/data``` и ```result``` для ```/var/result```.
|
||||
|
||||
|
||||
## [Видео](https://drive.google.com/file/d/1eBbIDgTo3MF4EeM677EPEKgJEINekaC0/view?usp=drive_link)
|
||||
@@ -1 +0,0 @@
|
||||
34 905 63 92 74 9 3 25 8 0 2 4 24 452 94 6 2 4 2 65 83 73 672 47 23 21 1
|
||||
@@ -1 +0,0 @@
|
||||
4 9 6 320 75 348 12 75 94 63 45 23 3
|
||||
@@ -1 +0,0 @@
|
||||
5 34 7 9 6 43 5 768 4 23 1 3 657 534 4 3 87 6 9 8 56 37 525 5 7 3 2 65 4 86 7 295 473 254 633 4 45 2
|
||||
@@ -1,18 +0,0 @@
|
||||
services:
|
||||
|
||||
worker_one:
|
||||
container_name: worker_one
|
||||
build:
|
||||
dockerfile: ./worker-1
|
||||
volumes:
|
||||
- ./data:/var/data
|
||||
- ./result:/var/result
|
||||
|
||||
worker_two:
|
||||
container_name: worker_two
|
||||
build:
|
||||
dockerfile: ./worker-2
|
||||
volumes:
|
||||
- ./result:/var/result
|
||||
depends_on:
|
||||
- worker_one
|
||||
@@ -1 +0,0 @@
|
||||
5 34 7 9 6 43 5 768 4 23 1 3 657 534 4 3 87 6 9 8 56 37 525 5 7 3 2 65 4 86 7 295 473 254 633 4 45 2
|
||||
@@ -1 +0,0 @@
|
||||
10
|
||||
@@ -1,11 +0,0 @@
|
||||
# Использую базовый образ Python
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Устанавливаю рабочую директорию внутри контейнера
|
||||
WORKDIR /app
|
||||
|
||||
# Копирую все файлы в контейнер
|
||||
COPY worker_1.py .
|
||||
|
||||
# Команда для запуска Python-скрипта
|
||||
CMD ["python", "worker_1.py"]
|
||||
@@ -1,27 +0,0 @@
|
||||
import os
|
||||
import shutil
|
||||
|
||||
# Ищет в каталоге /var/data самый большой по объёму файл и перекладывает его в /var/result/data.txt.
|
||||
print("start worker_1")
|
||||
dir_data = "/var/data"
|
||||
dir_res = "/var/result"
|
||||
|
||||
if not os.path.exists(dir_data):
|
||||
os.mkdir(dir_data)
|
||||
|
||||
if not os.path.exists(dir_res):
|
||||
os.mkdir(dir_res)
|
||||
|
||||
largest_file = None
|
||||
largest_size = 0
|
||||
|
||||
for root, dirs, files in os.walk(dir_data):
|
||||
for file in files:
|
||||
file_path = os.path.join(root, file)
|
||||
file_size = os.path.getsize(file_path)
|
||||
if file_size > largest_size:
|
||||
largest_size = file_size
|
||||
largest_file = file_path
|
||||
|
||||
if largest_file:
|
||||
shutil.copyfile(largest_file, dir_res + "/data.txt")
|
||||
@@ -1,11 +0,0 @@
|
||||
# Использую базовый образ Python
|
||||
FROM python:3.12-slim
|
||||
|
||||
# Устанавливаю рабочую директорию внутри контейнера
|
||||
WORKDIR /app
|
||||
|
||||
# Копирую все файлы в контейнер
|
||||
COPY worker_2.py .
|
||||
|
||||
# Команда для запуска Python-скрипта
|
||||
CMD ["python", "worker_2.py"]
|
||||
@@ -1,19 +0,0 @@
|
||||
# Сохраняет произведение первого и последнего числа из файла /var/result/data.txt в /var/result/result.txt.
|
||||
|
||||
print("start worker_2")
|
||||
|
||||
with open('/var/result/data.txt', 'r') as f:
|
||||
numbers = [int(num) for num in f.read().split() if num.isdigit()]
|
||||
|
||||
if numbers:
|
||||
first_number = numbers[0]
|
||||
last_number = numbers[-1]
|
||||
|
||||
result = first_number * last_number
|
||||
|
||||
with open('/var/result/result.txt', 'w') as f:
|
||||
f.write(f"{result}\n")
|
||||
|
||||
print(f"Получен результат - {result}")
|
||||
else:
|
||||
print("Результат не получен. Файл не содержит чисел")
|
||||
@@ -1,9 +0,0 @@
|
||||
# Переменные для базы данных Stream
|
||||
DB_HOST=postgres-db
|
||||
DB_PORT=5432
|
||||
DB_USER=postgres
|
||||
DB_PASSWORD=password
|
||||
DB_STREAM_NAME=streamdb
|
||||
|
||||
# Переменные для базы данных Message
|
||||
DB_MESSAGE_NAME=messagedb
|
||||
@@ -1,90 +0,0 @@
|
||||
# Отчет по лабораторной работе №3
|
||||
|
||||
## Поставленные задачи
|
||||
|
||||
1. Создать 2 микросервиса, реализующих CRUD на связанных сущностях.
|
||||
2. Реализовать механизм синхронного обмена сообщениями между микросервисами.
|
||||
3. Реализовать шлюз на основе прозрачного прокси-сервера nginx.
|
||||
|
||||
## Предметная область
|
||||
|
||||
Проект основан на системе управления стримами (трансляциями) и сообщениями.
|
||||
Каждый стрим представляет собой событие с такими параметрами, как название,
|
||||
время начала и окончания (окончание может быть null).
|
||||
Сообщения связаны с конкретными стримами и содержат следующие атрибуты: содержание,
|
||||
дата публикации, идентификатор стрима, к которому имеет отношение комментарий. Связь между сущностями один ко многим
|
||||
Два микросервиса выполняют раздельные функции: один управляет стримами, другой — сообщениями.
|
||||
Взаимодействие между ними происходит через HTTP-запросы.
|
||||
|
||||
## Запуск работы
|
||||
|
||||
1. Убедиться, что установлены необходимые технологии:
|
||||
- Docker: Платформа для контейнеризации приложений.
|
||||
- Docker Compose: Инструмент для запуска многоконтейнерных приложений на основе `docker-compose.yaml`. Обычно поставляется вместе с Docker. Чтобы проверить, установлена ли утилита, нужно запустить команду:
|
||||
```bash
|
||||
docker-compose --version
|
||||
```
|
||||
|
||||
2. В директории, где находится файл `docker-compose.yaml`, выполнить следующую команду для запуска всех сервисов:
|
||||
```bash
|
||||
docker-compose up --build
|
||||
```
|
||||
Эта команда сначала выполнит сборку, а затем запустит контейнеры.
|
||||
|
||||
3. После успешного запуска можно перейти к Swagger UI:
|
||||
- Message Swagger UI: [http://localhost/message-service/swagger/index.html](http://localhost/message-service/swagger/index.html#/).
|
||||
- Stream Swagger UI: [http://localhost/stream-service/swagger/index.html](http://localhost/message-service/swagger/index.html#/).
|
||||
|
||||
4. Stream сервис предоставляет следующие эндпоинты:
|
||||
- GET /streams — получить все стримы
|
||||
- POST /streams — создать новый стрим
|
||||
- GET /streams/{id} — получить стрим по ID
|
||||
- PUT /streams/{id} — обновить стрим по ID
|
||||
- DELETE /streams/{id} — удалить стрим по ID
|
||||
|
||||
Message сервис предоставляет:
|
||||
- GET /messages — получить все сообщения
|
||||
- POST /messages — создать новое сообщение
|
||||
- GET /messages/{id} — получить сообщение по ID
|
||||
- GET /messages/all/{streamId} — получить все сообщения, которые относятся к streamId
|
||||
- PUT /messages/{id} — обновить сообщение по ID
|
||||
- DELETE /messages/{id} — удалить сообщение по ID
|
||||
|
||||
## Технологии
|
||||
|
||||
1. Golang: основной язык программирования для микросервисов.
|
||||
2. PostgreSQL: база данных для хранения данных о стримах и сообщениях.
|
||||
3. Docker & Docker Compose: для контейнеризации сервисов и удобного развертывания.
|
||||
4. Swagger UI: для документации и тестирования API.
|
||||
5. Nginx: для проксирования запросов между клиентом и микросервисами.
|
||||
6. Gorilla Mux: маршрутизация запросов в Go.
|
||||
7. Zerolog: логирование ошибок и действий.
|
||||
|
||||
## Архитектура
|
||||
|
||||
Проект реализован на основе микросервисной архитектуры. Каждый сервис (Stream и Message)
|
||||
использует свою собственную базу данных (всего их две и в каждой БД по одной таблице) и предоставляет
|
||||
свои эндпоинты для работы с данными. Используются Docker и Docker Compose для управления окружением и
|
||||
запуска сервисов.
|
||||
|
||||
## Ход работы
|
||||
|
||||
1. **Микросервисная архитектура**: Проект разделен на два микросервиса: один для управления стримами,
|
||||
другой — для управления сообщениями. Каждый сервис имеет свой собственный набор функций, таблицы
|
||||
в базе данных и собственные эндпоинты для взаимодействия с клиентом.
|
||||
|
||||
2. **Реализация взаимодействия между микросервисами**: Stream-сервис предоставляет заголовки для стримов,
|
||||
которые затем использует Message-сервис для работы с сообщениями, привязанными к стримам.
|
||||
Взаимодействие реализовано через HTTP-запросы между сервисами.
|
||||
|
||||
3. **Использование Swagger**: Для каждого сервиса настроена Swagger-документация. Это позволяет
|
||||
визуализировать и тестировать API прямо в браузере, что упрощает разработку и тестирование.
|
||||
|
||||
4. **Докеризация проекта**: Все микросервисы и вспомогательные сервисы, такие как база данных и Nginx,
|
||||
запускаются через Docker Compose. Это упрощает управление зависимостями и разворачивание проекта.
|
||||
|
||||
В коде присутствуют пояснительные комментарии.
|
||||
|
||||
## Демонстрационное видео
|
||||
|
||||
Видеозапись доступна по адресу: [https://vk.com/video193898050_456240870](https://vk.com/video193898050_456240870)
|
||||
@@ -1,64 +0,0 @@
|
||||
services:
|
||||
# Общая база данных для обоих сервисов
|
||||
postgres-db:
|
||||
image: postgres:13-alpine
|
||||
environment:
|
||||
POSTGRES_USER: ${DB_USER} # Общий пользователь базы данных
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD} # Пароль для базы данных
|
||||
POSTGRES_DB: ${DB_STREAM_NAME} # База данных для сервиса Stream
|
||||
ports:
|
||||
- "5432:5432" # Порт базы данных
|
||||
volumes:
|
||||
- postgres-db-data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${DB_USER}"]
|
||||
interval: 20s
|
||||
timeout: 20s
|
||||
retries: 10
|
||||
networks:
|
||||
- network
|
||||
|
||||
# Сервис Stream
|
||||
stream-service:
|
||||
build: ./streamService
|
||||
env_file:
|
||||
- .env
|
||||
networks:
|
||||
- network
|
||||
ports:
|
||||
- "8000:8000"
|
||||
depends_on:
|
||||
postgres-db:
|
||||
condition: service_healthy
|
||||
|
||||
# Сервис Message
|
||||
message-service:
|
||||
build: ./messageService
|
||||
env_file:
|
||||
- .env
|
||||
networks:
|
||||
- network
|
||||
ports:
|
||||
- "8080:8080"
|
||||
depends_on:
|
||||
postgres-db:
|
||||
condition: service_healthy
|
||||
|
||||
nginx:
|
||||
image: nginx
|
||||
ports:
|
||||
- "80:80"
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf
|
||||
networks:
|
||||
- network
|
||||
depends_on:
|
||||
- stream-service
|
||||
- message-service
|
||||
|
||||
networks:
|
||||
network:
|
||||
driver: bridge
|
||||
|
||||
volumes:
|
||||
postgres-db-data:
|
||||
@@ -1,14 +0,0 @@
|
||||
FROM golang:1.23-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN go build -o message_main ./cmd/message_main.go
|
||||
|
||||
EXPOSE 8080
|
||||
|
||||
CMD ["./message_main"]
|
||||
@@ -1,64 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog"
|
||||
httpSwagger "github.com/swaggo/http-swagger"
|
||||
"log"
|
||||
_ "messageService/docs"
|
||||
"messageService/internal/app/database"
|
||||
"messageService/internal/app/handlers"
|
||||
"messageService/internal/app/repositories"
|
||||
"messageService/internal/app/services"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Настройка логирования
|
||||
logFile, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not open log file: %v", err)
|
||||
}
|
||||
defer func(logFile *os.File) {
|
||||
err := logFile.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(logFile)
|
||||
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
logger := zerolog.New(logFile).With().Timestamp().Logger()
|
||||
|
||||
// Инициализация базы данных
|
||||
db, err := database.InitMessageDB()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not connect to the database: %v", err)
|
||||
}
|
||||
|
||||
// Инициализация репозитория и сервиса
|
||||
messageRepo := repositories.NewMessageRepository(db)
|
||||
messageService := services.NewMessageService(messageRepo)
|
||||
|
||||
// Инициализация маршрутизатора
|
||||
router := mux.NewRouter()
|
||||
|
||||
// Создаем StreamClient
|
||||
streamClient := services.NewStreamClient("http://stream-service:8000", 5*time.Second)
|
||||
|
||||
// Регистрация хендлеров
|
||||
handlers.RegisterMessageRoutes(router, messageService, streamClient)
|
||||
|
||||
// Swagger
|
||||
router.HandleFunc("/doc.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "docs/doc.json")
|
||||
}).Methods("GET")
|
||||
|
||||
// Route for Swagger UI
|
||||
router.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
|
||||
|
||||
// Запуск сервера
|
||||
logger.Info().Msg("Server started at http://localhost:8080")
|
||||
logger.Fatal().Err(http.ListenAndServe(":8080", router)).Msg("Server crashed")
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"contact": {},
|
||||
"version": "",
|
||||
"title": ""
|
||||
},
|
||||
"paths": {
|
||||
"/message-service/messages": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех сообщений",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить все сообщения",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новое сообщение",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Создать сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message-service/messages/all/{streamId}": {
|
||||
"get": {
|
||||
"description": "Возвращает список сообщений с указанным StreamID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить список сообщений по StreamID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "StreamID сообщения",
|
||||
"name": "streamId",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.MessageResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message-service/messages/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает сообщение с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить сообщение по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные сообщения по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Обновить данные сообщения",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет сообщение по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Удалить сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Message": {
|
||||
"description": "Сообщение",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"description": "Содержание комментария",
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"description": "Время отправления комментария",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор сообщения",
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"models.MessageResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_title": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,269 +0,0 @@
|
||||
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||
package docs
|
||||
|
||||
import "github.com/swaggo/swag"
|
||||
|
||||
const docTemplate = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{escape .Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"contact": {},
|
||||
"version": "{{.Version}}"
|
||||
},
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/message-service/messages": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех сообщений",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить все сообщения",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новое сообщение",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Создать сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message-service/messages/all/{streamId}": {
|
||||
"get": {
|
||||
"description": "Возвращает список сообщений с указанным StreamID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить список сообщений по StreamID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "StreamID сообщения",
|
||||
"name": "streamId",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.MessageResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/message-service/messages/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает сообщение с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить сообщение по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные сообщения по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Обновить данные сообщения",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет сообщение по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Удалить сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Message": {
|
||||
"description": "Сообщение",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"description": "Содержание комментария",
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"description": "Время отправления комментария",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор сообщения",
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"models.MessageResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_title": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||
var SwaggerInfo = &swag.Spec{
|
||||
Version: "",
|
||||
Host: "",
|
||||
BasePath: "",
|
||||
Schemes: []string{},
|
||||
Title: "",
|
||||
Description: "",
|
||||
InfoInstanceName: "swagger",
|
||||
SwaggerTemplate: docTemplate,
|
||||
}
|
||||
|
||||
func init() {
|
||||
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"contact": {},
|
||||
"version": "",
|
||||
"title": ""
|
||||
},
|
||||
"paths": {
|
||||
"/messages": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех сообщений",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить все сообщения",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новое сообщение",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Создать сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/messages/all/{streamId}": {
|
||||
"get": {
|
||||
"description": "Возвращает список сообщений с указанным StreamID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить список сообщений по StreamID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "StreamID сообщения",
|
||||
"name": "streamId",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.MessageResponse"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/messages/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает сообщение с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Получить сообщение по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные сообщения по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Обновить данные сообщения",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные сообщения",
|
||||
"name": "message",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Message"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет сообщение по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"messages"
|
||||
],
|
||||
"summary": "Удалить сообщение",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID сообщения",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Message": {
|
||||
"description": "Сообщение",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"description": "Содержание комментария",
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"description": "Время отправления комментария",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор сообщения",
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
}
|
||||
}
|
||||
},
|
||||
"models.MessageResponse": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"content": {
|
||||
"type": "string"
|
||||
},
|
||||
"created_at": {
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer"
|
||||
},
|
||||
"stream_title": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
definitions:
|
||||
models.Message:
|
||||
description: Сообщение
|
||||
properties:
|
||||
content:
|
||||
description: Содержание комментария
|
||||
type: string
|
||||
created_at:
|
||||
description: Время отправления комментария
|
||||
example: "2024-10-04T14:48:00Z"
|
||||
type: string
|
||||
id:
|
||||
description: Идентификатор сообщения
|
||||
type: integer
|
||||
stream_id:
|
||||
description: Идентификатор стрима
|
||||
type: integer
|
||||
type: object
|
||||
models.MessageResponse:
|
||||
properties:
|
||||
content:
|
||||
type: string
|
||||
created_at:
|
||||
example: "2024-10-04T14:48:00Z"
|
||||
type: string
|
||||
id:
|
||||
type: integer
|
||||
stream_title:
|
||||
type: string
|
||||
type: object
|
||||
info:
|
||||
contact: { }
|
||||
version: '2.0'
|
||||
title: 'API'
|
||||
paths:
|
||||
/messages:
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает список всех сообщений
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/models.Message'
|
||||
type: array
|
||||
summary: Получить все сообщения
|
||||
tags:
|
||||
- messages
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Создает новое сообщение
|
||||
parameters:
|
||||
- description: Данные сообщения
|
||||
in: body
|
||||
name: message
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/models.Message'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Message'
|
||||
summary: Создать сообщение
|
||||
tags:
|
||||
- messages
|
||||
/messages/{id}:
|
||||
delete:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Удаляет сообщение по ID
|
||||
parameters:
|
||||
- description: ID сообщения
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
summary: Удалить сообщение
|
||||
tags:
|
||||
- messages
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает сообщение с указанным ID
|
||||
parameters:
|
||||
- description: ID сообщения
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Message'
|
||||
summary: Получить сообщение по ID
|
||||
tags:
|
||||
- messages
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Обновляет данные сообщения по ID
|
||||
parameters:
|
||||
- description: ID сообщения
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Обновленные данные сообщения
|
||||
in: body
|
||||
name: message
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/models.Message'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Message'
|
||||
summary: Обновить данные сообщения
|
||||
tags:
|
||||
- messages
|
||||
/messages/all/{streamId}:
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает список сообщений с указанным StreamID
|
||||
parameters:
|
||||
- description: StreamID сообщения
|
||||
in: path
|
||||
name: streamId
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/models.MessageResponse'
|
||||
type: array
|
||||
summary: Получить список сообщений по StreamID
|
||||
tags:
|
||||
- messages
|
||||
swagger: "2.0"
|
||||
@@ -1,39 +0,0 @@
|
||||
module messageService
|
||||
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/rs/zerolog v1.33.0
|
||||
github.com/swaggo/http-swagger v1.3.4
|
||||
github.com/swaggo/swag v1.8.1
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.0 // indirect
|
||||
github.com/go-openapi/spec v0.20.6 // indirect
|
||||
github.com/go-openapi/swag v0.19.15 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe // indirect
|
||||
golang.org/x/crypto v0.24.0 // indirect
|
||||
golang.org/x/net v0.26.0 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.21.0 // indirect
|
||||
golang.org/x/text v0.16.0 // indirect
|
||||
golang.org/x/tools v0.22.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
@@ -1,59 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
"messageService/internal/app/models"
|
||||
"os"
|
||||
)
|
||||
|
||||
// InitMessageDB инициализирует подключение к базе данных для микросервиса Message
|
||||
func InitMessageDB() (*gorm.DB, error) {
|
||||
host := os.Getenv("DB_HOST")
|
||||
port := os.Getenv("DB_PORT")
|
||||
user := os.Getenv("DB_USER")
|
||||
password := os.Getenv("DB_PASSWORD")
|
||||
dbname := os.Getenv("DB_MESSAGE_NAME")
|
||||
|
||||
// Строка подключения без указания имени базы данных
|
||||
dsn := fmt.Sprintf("host=%s user=%s password=%s port=%s sslmode=disable", host, user, password, port)
|
||||
|
||||
// Подключаемся к PostgreSQL без указания базы данных
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info), // Включаем логирование для отладки
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Проверяем существование базы данных
|
||||
var exists bool
|
||||
if err := db.Raw("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = ?)", dbname).Scan(&exists).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Если база данных не существует, создаем ее
|
||||
if !exists {
|
||||
if err := db.Exec(fmt.Sprintf("CREATE DATABASE %s;", dbname)).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
// Подключаемся к только что созданной базе данных
|
||||
dsn = fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable", host, user, password, dbname, port)
|
||||
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Info),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Автоматическая миграция для Message
|
||||
if err := db.AutoMigrate(&models.Message{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
@@ -1,244 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"messageService/internal/app/models"
|
||||
"messageService/internal/app/services"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func RegisterMessageRoutes(router *mux.Router, svc services.MessageService, streamSvc services.StreamClient) {
|
||||
router.HandleFunc("/messages", GetAllMessages(svc, streamSvc)).Methods("GET")
|
||||
router.HandleFunc("/messages/{id}", GetMessage(svc, streamSvc)).Methods("GET")
|
||||
router.HandleFunc("/messages/all/{streamId}", GetMessagesByStreamID(svc, streamSvc)).Methods("GET")
|
||||
router.HandleFunc("/messages", CreateMessage(svc)).Methods("POST")
|
||||
router.HandleFunc("/messages/{id}", UpdateMessage(svc)).Methods("PUT")
|
||||
router.HandleFunc("/messages/{id}", DeleteMessage(svc)).Methods("DELETE")
|
||||
}
|
||||
|
||||
// GetAllMessages godoc
|
||||
// @Summary Получить все сообщения
|
||||
// @Description Возвращает список всех сообщений
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} models.Message
|
||||
// @Router /messages [get]
|
||||
func GetAllMessages(svc services.MessageService, streamSvc services.StreamClient) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
messages, err := svc.GetAllMessages()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var response []models.MessageResponse
|
||||
for _, message := range messages {
|
||||
stream, err := streamSvc.GetStreamTitleByID(message.StreamID)
|
||||
log.Printf("Result: %s", stream)
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
response = append(response, models.MessageResponse{
|
||||
ID: message.ID,
|
||||
Content: message.Content,
|
||||
StreamTitle: stream,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
err = json.NewEncoder(w).Encode(response)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetMessagesByStreamID godoc
|
||||
// @Summary Получить список сообщений по StreamID
|
||||
// @Description Возвращает список сообщений с указанным StreamID
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param streamId path int true "StreamID сообщения"
|
||||
// @Success 200 {array} models.MessageResponse
|
||||
// @Router /messages/all/{streamId} [get]
|
||||
func GetMessagesByStreamID(svc services.MessageService, streamSvc services.StreamClient) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := mux.Vars(r)["streamId"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid StreamID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
messages, err := svc.GetMessagesByStreamID(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
var response []models.MessageResponse
|
||||
for _, message := range messages {
|
||||
stream, err := streamSvc.GetStreamTitleByID(message.StreamID)
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
response = append(response, models.MessageResponse{
|
||||
ID: message.ID,
|
||||
Content: message.Content,
|
||||
StreamTitle: stream,
|
||||
CreatedAt: message.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
err = json.NewEncoder(w).Encode(response)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetMessage godoc
|
||||
// @Summary Получить сообщение по ID
|
||||
// @Description Возвращает сообщение с указанным ID
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID сообщения"
|
||||
// @Success 200 {object} models.Message
|
||||
// @Router /messages/{id} [get]
|
||||
func GetMessage(svc services.MessageService, streamSvc services.StreamClient) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
message, err := svc.GetMessageByID(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, "Message not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var response models.MessageResponse
|
||||
stream, err := streamSvc.GetStreamTitleByID(message.StreamID)
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
response = models.MessageResponse{
|
||||
ID: message.ID,
|
||||
Content: message.Content,
|
||||
StreamTitle: stream,
|
||||
CreatedAt: message.CreatedAt,
|
||||
}
|
||||
|
||||
err = json.NewEncoder(w).Encode(response)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CreateMessage godoc
|
||||
// @Summary Создать сообщение
|
||||
// @Description Создает новое сообщение
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param message body models.Message true "Данные сообщения"
|
||||
// @Success 200 {object} models.Message
|
||||
// @Router /messages [post]
|
||||
func CreateMessage(svc services.MessageService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var message models.Message
|
||||
err := json.NewDecoder(r.Body).Decode(&message)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = svc.CreateMessage(&message)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
err = json.NewEncoder(w).Encode(message)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateMessage godoc
|
||||
// @Summary Обновить данные сообщения
|
||||
// @Description Обновляет данные сообщения по ID
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID сообщения"
|
||||
// @Param message body models.Message true "Обновленные данные сообщения"
|
||||
// @Success 200 {object} models.Message
|
||||
// @Router /messages/{id} [put]
|
||||
func UpdateMessage(svc services.MessageService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var message models.Message
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&message); err != nil {
|
||||
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
message.ID = uint(id)
|
||||
err = svc.UpdateMessage(&message)
|
||||
if err != nil {
|
||||
http.Error(w, "Message not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(w).Encode(message)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteMessage godoc
|
||||
// @Summary Удалить сообщение
|
||||
// @Description Удаляет сообщение по ID
|
||||
// @Tags messages
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID сообщения"
|
||||
// @Success 204 "No Content"
|
||||
// @Router /messages/{id} [delete]
|
||||
func DeleteMessage(svc services.MessageService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = svc.DeleteMessage(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, "Message not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Message представляет сообщение в системе
|
||||
// @Description Сообщение
|
||||
type Message struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"` // Идентификатор сообщения
|
||||
StreamID uint `json:"stream_id"` // Идентификатор стрима
|
||||
Content string `json:"content"` // Содержание комментария
|
||||
CreatedAt time.Time `json:"created_at" example:"2024-10-04T14:48:00Z"` // Время отправления комментария
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type MessageResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Content string `json:"content"`
|
||||
StreamTitle string `json:"stream_title"`
|
||||
CreatedAt time.Time `json:"created_at" example:"2024-10-04T14:48:00Z"`
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
package models
|
||||
|
||||
type StreamResponse struct {
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
StartedAt string `json:"started_at"`
|
||||
EndedAt *string `json:"ended_at"`
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"messageService/internal/app/models"
|
||||
)
|
||||
|
||||
type MessageRepository interface {
|
||||
GetAllMessages() ([]models.Message, error)
|
||||
GetMessageByID(id uint) (*models.Message, error)
|
||||
GetMessagesByStreamID(streamID uint) ([]models.Message, error)
|
||||
CreateMessage(message *models.Message) error
|
||||
UpdateMessage(message *models.Message) error
|
||||
DeleteMessage(id uint) error
|
||||
}
|
||||
|
||||
type messageRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewMessageRepository(db *gorm.DB) MessageRepository {
|
||||
return &messageRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *messageRepository) GetAllMessages() ([]models.Message, error) {
|
||||
var messages []models.Message
|
||||
if err := r.db.Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func (r *messageRepository) GetMessageByID(id uint) (*models.Message, error) {
|
||||
var message models.Message
|
||||
if err := r.db.First(&message, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &message, nil
|
||||
}
|
||||
|
||||
func (r *messageRepository) GetMessagesByStreamID(streamID uint) ([]models.Message, error) {
|
||||
var messages []models.Message
|
||||
if err := r.db.Where("stream_id = ?", streamID).Find(&messages).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
func (r *messageRepository) CreateMessage(message *models.Message) error {
|
||||
return r.db.Create(message).Error
|
||||
}
|
||||
|
||||
func (r *messageRepository) UpdateMessage(message *models.Message) error {
|
||||
var existingMessage models.Message
|
||||
if err := r.db.First(&existingMessage, message.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.db.Model(&existingMessage).Updates(message).Error
|
||||
}
|
||||
|
||||
func (r *messageRepository) DeleteMessage(id uint) error {
|
||||
return r.db.Delete(&models.Message{}, id).Error
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"messageService/internal/app/models"
|
||||
"messageService/internal/app/repositories"
|
||||
)
|
||||
|
||||
type MessageService interface {
|
||||
GetAllMessages() ([]models.Message, error)
|
||||
GetMessagesByStreamID(streamId uint) ([]models.Message, error)
|
||||
GetMessageByID(id uint) (*models.Message, error)
|
||||
CreateMessage(message *models.Message) error
|
||||
UpdateMessage(message *models.Message) error
|
||||
DeleteMessage(id uint) error
|
||||
}
|
||||
|
||||
type messageService struct {
|
||||
repo repositories.MessageRepository
|
||||
}
|
||||
|
||||
func NewMessageService(repo repositories.MessageRepository) MessageService {
|
||||
return &messageService{repo}
|
||||
}
|
||||
|
||||
func (s *messageService) GetAllMessages() ([]models.Message, error) {
|
||||
return s.repo.GetAllMessages()
|
||||
}
|
||||
|
||||
func (s *messageService) GetMessagesByStreamID(streamId uint) ([]models.Message, error) {
|
||||
return s.repo.GetMessagesByStreamID(streamId)
|
||||
}
|
||||
|
||||
func (s *messageService) GetMessageByID(id uint) (*models.Message, error) {
|
||||
return s.repo.GetMessageByID(id)
|
||||
}
|
||||
|
||||
func (s *messageService) CreateMessage(message *models.Message) error {
|
||||
return s.repo.CreateMessage(message)
|
||||
}
|
||||
|
||||
func (s *messageService) UpdateMessage(message *models.Message) error {
|
||||
return s.repo.UpdateMessage(message)
|
||||
}
|
||||
|
||||
func (s *messageService) DeleteMessage(id uint) error {
|
||||
return s.repo.DeleteMessage(id)
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"messageService/internal/app/models"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type StreamClient interface {
|
||||
GetStreamTitleByID(streamId uint) (string, error)
|
||||
}
|
||||
|
||||
type streamClient struct {
|
||||
BaseURL string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
func NewStreamClient(baseURL string, timeout time.Duration) StreamClient {
|
||||
return &streamClient{
|
||||
BaseURL: baseURL,
|
||||
Timeout: timeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *streamClient) GetStreamTitleByID(streamID uint) (string, error) {
|
||||
client := &http.Client{Timeout: c.Timeout}
|
||||
url := fmt.Sprintf("%s/streams/%d", c.BaseURL, streamID)
|
||||
log.Printf(url)
|
||||
|
||||
resp, err := client.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer func(Body io.ReadCloser) {
|
||||
err := Body.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(resp.Body)
|
||||
|
||||
log.Printf("Response Status: %s", resp.Status)
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
log.Printf("Response Body: %s", body)
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return "", fmt.Errorf("failed to get stream title: %s", resp.Status)
|
||||
}
|
||||
|
||||
var stream models.StreamResponse
|
||||
if err := json.Unmarshal(body, &stream); err != nil {
|
||||
log.Printf("Unmarshal error: %s", err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
log.Printf("Name: %s", stream.Title)
|
||||
|
||||
return stream.Title, nil
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
server {
|
||||
listen 80;
|
||||
server_name localhost;
|
||||
|
||||
# Прокси для Stream-сервиса
|
||||
location /stream-service/ {
|
||||
proxy_pass http://stream-service:8000/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
add_header 'Access-Control-Allow-Origin' '*';
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
|
||||
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization';
|
||||
|
||||
}
|
||||
|
||||
# Прокси для Message-сервиса
|
||||
location /message-service/ {
|
||||
proxy_pass http://message-service:8080/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
add_header 'Access-Control-Allow-Origin' '*';
|
||||
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
|
||||
add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization';
|
||||
}
|
||||
|
||||
# Прокси для Swagger (Stream-сервис)
|
||||
location /stream-service/swagger/ {
|
||||
proxy_pass http://stream-service:8000/swagger/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# Прокси для Swagger (Message-сервис)
|
||||
location /message-service/swagger/ {
|
||||
proxy_pass http://message-service:8080/swagger/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
location /stream-service/doc.json {
|
||||
proxy_pass http://stream-service:8000/doc.json;
|
||||
}
|
||||
|
||||
location /message-service/doc.json {
|
||||
proxy_pass http://message-service:8080/doc.json;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
FROM golang:1.23-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN go build -o stream_main ./cmd/stream_main.go
|
||||
|
||||
EXPOSE 8000
|
||||
|
||||
CMD ["./stream_main"]
|
||||
@@ -1,59 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/rs/zerolog"
|
||||
httpSwagger "github.com/swaggo/http-swagger"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
_ "streamService/docs"
|
||||
"streamService/internal/app/database"
|
||||
"streamService/internal/app/handlers"
|
||||
"streamService/internal/app/repositories"
|
||||
"streamService/internal/app/services"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Настройка логирования
|
||||
logFile, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
log.Fatalf("Could not open log file: %v", err)
|
||||
}
|
||||
defer func(logFile *os.File) {
|
||||
err := logFile.Close()
|
||||
if err != nil {
|
||||
|
||||
}
|
||||
}(logFile)
|
||||
|
||||
zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
|
||||
logger := zerolog.New(logFile).With().Timestamp().Logger()
|
||||
|
||||
// Инициализация базы данных
|
||||
db, err := database.InitStreamDB()
|
||||
if err != nil {
|
||||
log.Fatalf("Could not connect to the database: %v", err)
|
||||
}
|
||||
|
||||
// Инициализация репозитория и сервиса
|
||||
streamRepo := repositories.NewStreamRepository(db)
|
||||
streamService := services.NewStreamService(streamRepo)
|
||||
|
||||
// Инициализация маршрутизатора
|
||||
router := mux.NewRouter()
|
||||
|
||||
// Регистрация хендлеров
|
||||
handlers.RegisterStreamRoutes(router, streamService)
|
||||
|
||||
// Swagger
|
||||
router.HandleFunc("/doc.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.ServeFile(w, r, "docs/doc.json")
|
||||
}).Methods("GET")
|
||||
|
||||
// Route for Swagger UI
|
||||
router.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)
|
||||
|
||||
logger.Info().Msg("Server started at http://localhost:8000")
|
||||
logger.Fatal().Err(http.ListenAndServe(":8000", router)).Msg("Server crashed")
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"contact": {},
|
||||
"version": "",
|
||||
"title": ""
|
||||
},
|
||||
"paths": {
|
||||
"/stream-service/streams": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех стримов",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить все стримы",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новый стрим",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Создать стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные стримы",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/stream-service/streams/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает стрим с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить стрим по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные стрима по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Обновить данные стрима",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные стрима",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет стрим по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Удалить стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Stream": {
|
||||
"description": "Стрим",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ended_at": {
|
||||
"description": "Время окончания стрима",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
},
|
||||
"started_at": {
|
||||
"description": "Время запуска стрима",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"title": {
|
||||
"description": "Название стрима",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,216 +0,0 @@
|
||||
// Package docs Code generated by swaggo/swag. DO NOT EDIT
|
||||
package docs
|
||||
|
||||
import "github.com/swaggo/swag"
|
||||
|
||||
const docTemplate = `{
|
||||
"schemes": {{ marshal .Schemes }},
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"description": "{{escape .Description}}",
|
||||
"title": "{{.Title}}",
|
||||
"contact": {},
|
||||
"version": "{{.Version}}"
|
||||
},
|
||||
"host": "{{.Host}}",
|
||||
"basePath": "{{.BasePath}}",
|
||||
"paths": {
|
||||
"/stream-service/streams": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех стримов",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить все стримы",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новый стрим",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Создать стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные стримы",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/stream-service/streams/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает стрим с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить стрим по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные стрима по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Обновить данные стрима",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные стрима",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет стрим по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Удалить стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Stream": {
|
||||
"description": "Стрим",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ended_at": {
|
||||
"description": "Время окончания стрима",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
},
|
||||
"started_at": {
|
||||
"description": "Время запуска стрима",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"title": {
|
||||
"description": "Название стрима",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}`
|
||||
|
||||
// SwaggerInfo holds exported Swagger Info so clients can modify it
|
||||
var SwaggerInfo = &swag.Spec{
|
||||
Version: "",
|
||||
Host: "",
|
||||
BasePath: "",
|
||||
Schemes: []string{},
|
||||
Title: "",
|
||||
Description: "",
|
||||
InfoInstanceName: "swagger",
|
||||
SwaggerTemplate: docTemplate,
|
||||
}
|
||||
|
||||
func init() {
|
||||
swag.Register(SwaggerInfo.InstanceName(), SwaggerInfo)
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
{
|
||||
"swagger": "2.0",
|
||||
"info": {
|
||||
"contact": {},
|
||||
"version": "",
|
||||
"title": ""
|
||||
},
|
||||
"paths": {
|
||||
"/streams": {
|
||||
"get": {
|
||||
"description": "Возвращает список всех стримов",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить все стримы",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"description": "Создает новый стрим",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Создать стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"description": "Данные стримы",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/streams/{id}": {
|
||||
"get": {
|
||||
"description": "Возвращает стрим с указанным ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Получить стрим по ID",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"put": {
|
||||
"description": "Обновляет данные стрима по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Обновить данные стрима",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"description": "Обновленные данные стрима",
|
||||
"name": "stream",
|
||||
"in": "body",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"schema": {
|
||||
"$ref": "#/definitions/models.Stream"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"delete": {
|
||||
"description": "Удаляет стрим по ID",
|
||||
"consumes": [
|
||||
"application/json"
|
||||
],
|
||||
"produces": [
|
||||
"application/json"
|
||||
],
|
||||
"tags": [
|
||||
"streams"
|
||||
],
|
||||
"summary": "Удалить стрим",
|
||||
"parameters": [
|
||||
{
|
||||
"type": "integer",
|
||||
"description": "ID стрима",
|
||||
"name": "id",
|
||||
"in": "path",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"responses": {
|
||||
"204": {
|
||||
"description": "No Content"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"definitions": {
|
||||
"models.Stream": {
|
||||
"description": "Стрим",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ended_at": {
|
||||
"description": "Время окончания стрима",
|
||||
"type": "string"
|
||||
},
|
||||
"id": {
|
||||
"description": "Идентификатор стрима",
|
||||
"type": "integer"
|
||||
},
|
||||
"started_at": {
|
||||
"description": "Время запуска стрима",
|
||||
"type": "string",
|
||||
"example": "2024-10-04T14:48:00Z"
|
||||
},
|
||||
"title": {
|
||||
"description": "Название стрима",
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
definitions:
|
||||
models.Stream:
|
||||
description: Стрим
|
||||
properties:
|
||||
ended_at:
|
||||
description: Время окончания стрима
|
||||
type: string
|
||||
id:
|
||||
description: Идентификатор стрима
|
||||
type: integer
|
||||
started_at:
|
||||
description: Время запуска стрима
|
||||
example: "2024-10-04T14:48:00Z"
|
||||
type: string
|
||||
title:
|
||||
description: Название стрима
|
||||
type: string
|
||||
type: object
|
||||
info:
|
||||
contact: { }
|
||||
version: '2.0'
|
||||
title: 'API'
|
||||
paths:
|
||||
/streams:
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает список всех стримов
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
items:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
type: array
|
||||
summary: Получить все стримы
|
||||
tags:
|
||||
- streams
|
||||
post:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Создает новый стрим
|
||||
parameters:
|
||||
- description: Данные стримы
|
||||
in: body
|
||||
name: stream
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
summary: Создать стрим
|
||||
tags:
|
||||
- streams
|
||||
/streams/{id}:
|
||||
delete:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Удаляет стрим по ID
|
||||
parameters:
|
||||
- description: ID стрима
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"204":
|
||||
description: No Content
|
||||
summary: Удалить стрим
|
||||
tags:
|
||||
- streams
|
||||
get:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Возвращает стрим с указанным ID
|
||||
parameters:
|
||||
- description: ID стрима
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
summary: Получить стрим по ID
|
||||
tags:
|
||||
- streams
|
||||
put:
|
||||
consumes:
|
||||
- application/json
|
||||
description: Обновляет данные стрима по ID
|
||||
parameters:
|
||||
- description: ID стрима
|
||||
in: path
|
||||
name: id
|
||||
required: true
|
||||
type: integer
|
||||
- description: Обновленные данные стрима
|
||||
in: body
|
||||
name: stream
|
||||
required: true
|
||||
schema:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
produces:
|
||||
- application/json
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
schema:
|
||||
$ref: '#/definitions/models.Stream'
|
||||
summary: Обновить данные стрима
|
||||
tags:
|
||||
- streams
|
||||
swagger: "2.0"
|
||||
@@ -1,39 +0,0 @@
|
||||
module streamService
|
||||
|
||||
go 1.23.2
|
||||
|
||||
require (
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/rs/zerolog v1.33.0
|
||||
github.com/swaggo/http-swagger v1.3.4
|
||||
github.com/swaggo/swag v1.8.1
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.12
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||
github.com/go-openapi/jsonreference v0.20.0 // indirect
|
||||
github.com/go-openapi/spec v0.20.6 // indirect
|
||||
github.com/go-openapi/swag v0.19.15 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
|
||||
github.com/jackc/pgx/v5 v5.5.5 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.1 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/josharian/intern v1.0.0 // indirect
|
||||
github.com/mailru/easyjson v0.7.6 // indirect
|
||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||
github.com/mattn/go-isatty v0.0.19 // indirect
|
||||
github.com/rogpeppe/go-internal v1.13.1 // indirect
|
||||
github.com/swaggo/files v0.0.0-20220610200504-28940afbdbfe // indirect
|
||||
golang.org/x/crypto v0.24.0 // indirect
|
||||
golang.org/x/net v0.26.0 // indirect
|
||||
golang.org/x/sync v0.7.0 // indirect
|
||||
golang.org/x/sys v0.21.0 // indirect
|
||||
golang.org/x/text v0.16.0 // indirect
|
||||
golang.org/x/tools v0.22.0 // indirect
|
||||
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||
)
|
||||
@@ -1,31 +0,0 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
"os"
|
||||
"streamService/internal/app/models"
|
||||
)
|
||||
|
||||
// InitStreamDB инициализирует подключение к базе данных для микросервиса Stream
|
||||
func InitStreamDB() (*gorm.DB, error) {
|
||||
host := os.Getenv("DB_HOST")
|
||||
port := os.Getenv("DB_PORT")
|
||||
user := os.Getenv("DB_USER")
|
||||
password := os.Getenv("DB_PASSWORD")
|
||||
dbname := os.Getenv("DB_STREAM_NAME")
|
||||
|
||||
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s sslmode=disable", host, user, password, dbname, port)
|
||||
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Автоматическая миграция для Stream
|
||||
if err := db.AutoMigrate(&models.Stream{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"streamService/internal/app/models"
|
||||
"streamService/internal/app/services"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
func RegisterStreamRoutes(router *mux.Router, svc services.StreamService) {
|
||||
router.HandleFunc("/streams", GetAllStreams(svc)).Methods("GET")
|
||||
router.HandleFunc("/streams/{id}", GetStream(svc)).Methods("GET")
|
||||
router.HandleFunc("/streams", CreateStream(svc)).Methods("POST")
|
||||
router.HandleFunc("/streams/{id}", UpdateStream(svc)).Methods("PUT")
|
||||
router.HandleFunc("/streams/{id}", DeleteStream(svc)).Methods("DELETE")
|
||||
}
|
||||
|
||||
// GetAllStreams godoc
|
||||
// @Summary Получить все стримы
|
||||
// @Description Возвращает список всех стримов
|
||||
// @Tags streams
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Success 200 {array} models.Stream
|
||||
// @Router /streams [get]
|
||||
func GetAllStreams(svc services.StreamService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
streams, err := svc.GetAllStreams()
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(w).Encode(streams)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetStream godoc
|
||||
// @Summary Получить стрим по ID
|
||||
// @Description Возвращает стрим с указанным ID
|
||||
// @Tags streams
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID стрима"
|
||||
// @Success 200 {object} models.Stream
|
||||
// @Router /streams/{id} [get]
|
||||
func GetStream(svc services.StreamService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
log.Printf("Response Body: %s", body)
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
stream, err := svc.GetStreamByID(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(w).Encode(stream)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CreateStream godoc
|
||||
// @Summary Создать стрим
|
||||
// @Description Создает новый стрим
|
||||
// @Tags streams
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param stream body models.Stream true "Данные стримы"
|
||||
// @Success 200 {object} models.Stream
|
||||
// @Router /streams [post]
|
||||
func CreateStream(svc services.StreamService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var stream models.Stream
|
||||
err := json.NewDecoder(r.Body).Decode(&stream)
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = svc.CreateStream(&stream)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
err = json.NewEncoder(w).Encode(stream)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateStream godoc
|
||||
// @Summary Обновить данные стрима
|
||||
// @Description Обновляет данные стрима по ID
|
||||
// @Tags streams
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID стрима"
|
||||
// @Param stream body models.Stream true "Обновленные данные стрима"
|
||||
// @Success 200 {object} models.Stream
|
||||
// @Router /streams/{id} [put]
|
||||
func UpdateStream(svc services.StreamService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var stream models.Stream
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
if err := json.NewDecoder(r.Body).Decode(&stream); err != nil {
|
||||
http.Error(w, "Failed to decode request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
stream.ID = uint(id)
|
||||
err = svc.UpdateStream(&stream)
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(w).Encode(stream)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DeleteStream godoc
|
||||
// @Summary Удалить стрим
|
||||
// @Description Удаляет стрим по ID
|
||||
// @Tags streams
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path int true "ID стрима"
|
||||
// @Success 204 "No Content"
|
||||
// @Router /streams/{id} [delete]
|
||||
func DeleteStream(svc services.StreamService) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
idStr := mux.Vars(r)["id"]
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = svc.DeleteStream(uint(id))
|
||||
if err != nil {
|
||||
http.Error(w, "Stream not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
// Stream представляет стрим в системе
|
||||
// @Description Стрим
|
||||
type Stream struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"` // Идентификатор стрима
|
||||
Title string `json:"title"` // Название стрима
|
||||
StartedAt time.Time `json:"started_at" example:"2024-10-04T14:48:00Z"` // Время запуска стрима
|
||||
EndedAt *time.Time `json:"ended_at"` // Время окончания стрима
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package repositories
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
"streamService/internal/app/models"
|
||||
)
|
||||
|
||||
type StreamRepository interface {
|
||||
GetAllStreams() ([]models.Stream, error)
|
||||
GetStreamByID(id uint) (*models.Stream, error)
|
||||
CreateStream(stream *models.Stream) error
|
||||
UpdateStream(stream *models.Stream) error
|
||||
DeleteStream(id uint) error
|
||||
}
|
||||
|
||||
type streamRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
func NewStreamRepository(db *gorm.DB) StreamRepository {
|
||||
return &streamRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *streamRepository) GetAllStreams() ([]models.Stream, error) {
|
||||
var streams []models.Stream
|
||||
if err := r.db.Find(&streams).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return streams, nil
|
||||
}
|
||||
|
||||
func (r *streamRepository) GetStreamByID(id uint) (*models.Stream, error) {
|
||||
var stream models.Stream
|
||||
if err := r.db.First(&stream, id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &stream, nil
|
||||
}
|
||||
|
||||
func (r *streamRepository) CreateStream(stream *models.Stream) error {
|
||||
return r.db.Create(stream).Error
|
||||
}
|
||||
|
||||
func (r *streamRepository) UpdateStream(stream *models.Stream) error {
|
||||
var existingStream models.Stream
|
||||
if err := r.db.First(&existingStream, stream.ID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return r.db.Model(&existingStream).Updates(stream).Error
|
||||
}
|
||||
|
||||
func (r *streamRepository) DeleteStream(id uint) error {
|
||||
return r.db.Delete(&models.Stream{}, id).Error
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"streamService/internal/app/models"
|
||||
"streamService/internal/app/repositories"
|
||||
)
|
||||
|
||||
type StreamService interface {
|
||||
GetAllStreams() ([]models.Stream, error)
|
||||
GetStreamByID(id uint) (*models.Stream, error)
|
||||
CreateStream(stream *models.Stream) error
|
||||
UpdateStream(stream *models.Stream) error
|
||||
DeleteStream(id uint) error
|
||||
}
|
||||
|
||||
type streamService struct {
|
||||
repo repositories.StreamRepository
|
||||
}
|
||||
|
||||
func NewStreamService(repo repositories.StreamRepository) StreamService {
|
||||
return &streamService{repo}
|
||||
}
|
||||
|
||||
func (s *streamService) GetAllStreams() ([]models.Stream, error) {
|
||||
return s.repo.GetAllStreams()
|
||||
}
|
||||
|
||||
func (s *streamService) GetStreamByID(id uint) (*models.Stream, error) {
|
||||
return s.repo.GetStreamByID(id)
|
||||
}
|
||||
|
||||
func (s *streamService) CreateStream(stream *models.Stream) error {
|
||||
return s.repo.CreateStream(stream)
|
||||
}
|
||||
|
||||
func (s *streamService) UpdateStream(stream *models.Stream) error {
|
||||
return s.repo.UpdateStream(stream)
|
||||
}
|
||||
|
||||
func (s *streamService) DeleteStream(id uint) error {
|
||||
return s.repo.DeleteStream(id)
|
||||
}
|
||||
Reference in New Issue
Block a user