티스토리 뷰

학습/AWS

DB 기초 완료

aigoia 2024. 3. 22. 09:26

 

 다이나모 디비에서 정보를 불러오는 것까지 완료했다. 

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.DataModel;
using Amazon.Lambda.Core;
using Amazon.Lambda.APIGatewayEvents;

// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))]

namespace HelloWorld
{ 
    public class Function
    {
        static HttpClient Client => new();

        static async Task<string> GetCallingIp()
        {
            Client.DefaultRequestHeaders.Accept.Clear();
            Client.DefaultRequestHeaders.Add("User-Agent", "AWS Lambda .Net Client");

            var massage = await Client.GetStringAsync("http://checkip.amazonaws.com/").ConfigureAwait(continueOnCapturedContext:false);

            return massage.Replace("\n","");
        }

        public async Task<APIGatewayProxyResponse> FunctionHandler(APIGatewayProxyResponse eventPayload, ILambdaContext context)
        {
            if (string.IsNullOrEmpty(eventPayload.Body))
            {
                return new APIGatewayProxyResponse
                {
                    Body = "Invalid request: Body is null or empty",
                    StatusCode = 400,
                    Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
                };
            }

            try
            {
                var eventToJob = JsonSerializer.Deserialize<Job>(eventPayload.Body);
                
                if (string.IsNullOrEmpty(eventToJob.Title))
                {
                    return new APIGatewayProxyResponse
                    {
                        Body = "Invalid request: Deserialize error",
                        StatusCode = 500,
                        Headers = new Dictionary<string, string> { { "Content-Type", "text/plain" } }
                    };
                }
        
                var dynamoContext = new DynamoDBContext(new AmazonDynamoDBClient());
                var jobContext = await dynamoContext.LoadAsync<Job>(eventToJob.Title);
        
                var location = await GetCallingIp();
                var body = new Dictionary<string, string>
                {
                    { "Job", jobContext.Title},
                    { "Job description", jobContext.Description}
                };

                return new APIGatewayProxyResponse
                {
                    Body = JsonSerializer.Serialize(body),
                    StatusCode = 200,
                    Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
                };
            }
            catch (Exception exception)
            {
                return new APIGatewayProxyResponse
                {
                    Body = $"Error occurred: {exception.Message}",
                    StatusCode = 500,
                    Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
                };
            }
        }
    }

    public class Job
    {
        [DynamoDBHashKey] 
        public string Title { get; set; }
        public string Description { get; set; }
    
        public Job() { }
    }
}

 

 기본 서버 코드이다.

using UnityEngine;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Unity.VisualScripting;

class NetworkManager : MonoBehaviour
{
    string URL => "";
    Job JobDate => new Job("Chef", "Chef makes cooking");
    HttpClient Client => new HttpClient();

    async void Start() => await Send();
    
    async Task Send()
    {
        var payload = JobDate.Serialize().json;
        var content = new StringContent(payload, Encoding.ASCII, "application/json");
        var response = await Client.PostAsync(URL, content);
        
        try
        {
            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                print("Server response: " + responseBody);
            }
            else
            {
                print("HTTP error code: " + response.StatusCode);
            }
        }
        catch (Exception exception)
        {
            print("Exception: " + exception.Message);
        }
    }
}

public class Job
{
    public string Title { get; set; }
    public string Description { get; set; }

    public Job(string title, string description)
    {
        Title = title;
        Description = description;
    }
}

 

 기본 유니티 코드이다. 

 

https://github.com/aigoia

 

aigoia - Overview

Goetita / Unity / Blender / TA . aigoia has 4 repositories available. Follow their code on GitHub.

github.com

 코드는 여기 올려 두었다.

 

'학습 > AWS' 카테고리의 다른 글

새로 컴퓨터에  (0) 2024.04.07
동영상 링크 관리  (0) 2024.04.05
자격인증 구현하기  (1) 2024.03.21
궁금했던 내용  (0) 2024.03.21
서버리스 람다 유니티 연결  (0) 2024.03.19