<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Adithyanunni on Medium]]></title>
        <description><![CDATA[Stories by Adithyanunni on Medium]]></description>
        <link>https://medium.com/@adithyanunni258?source=rss-e3f6af643d05------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OI82m8KIkPIdQ-uMclRvpg.jpeg</url>
            <title>Stories by Adithyanunni on Medium</title>
            <link>https://medium.com/@adithyanunni258?source=rss-e3f6af643d05------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 21:04:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adithyanunni258/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Seamless File Management in AWS S3 with Go: View, Upload, and Publish Like a Pro]]></title>
            <link>https://medium.com/@adithyanunni258/seamless-file-management-in-aws-s3-with-go-view-upload-and-publish-like-a-pro-ec006ef65cc3?source=rss-e3f6af643d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec006ef65cc3</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[s3-bucket]]></category>
            <category><![CDATA[postman]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[echo]]></category>
            <dc:creator><![CDATA[Adithyanunni]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 06:15:11 GMT</pubDate>
            <atom:updated>2024-09-13T06:15:11.669Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Introduction</strong></blockquote><ul><li><strong>Overview</strong>: Briefly introduce <strong>AWS S3</strong> and its importance for file storage.</li><li><strong>Goal</strong>: Explain what readers will learn — how to view, upload, and publish files in <strong>S3</strong> using <strong>Go</strong>.</li><li><strong>Implementation: </strong>will be using echo framework there will be two api upload and view/:filename</li></ul><h4>1. Introduction to AWS S3 and Go</h4><ul><li><strong>What is AWS S3?</strong>: A quick overview of <strong>AWS S3</strong> (Simple Storage Service) and its use cases.</li><li><strong>Why Use Go?</strong>: Benefits of using <strong>Go</strong> for interacting with <strong>AWS services</strong>, such as performance and concurrency.</li></ul><p><strong>2. Setting Up Aws s3 bucket</strong></p><ul><li><strong>Create a s3 bucket</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUj4SHQ3evFwSFm6xmfk-Q.png" /></figure><p>Keep all default options given by aws.</p><ul><li><strong>Create a iam user giving permission for s3</strong>:</li></ul><p>search for <strong>IAM </strong>then hover to users inthere create a new user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITAPsjl1huj2VrBDcZ9mXQ.png" /></figure><ul><li><strong>Set permission for the user</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUGVkYP1YfpH8hBAqmdfOw.png" /></figure><p>here i am giving AdministratorAccess it is not recommended there is default policies for <strong>s3</strong> you can search.</p><ul><li><strong>create the access key</strong>:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VYqMhocfFZr6y8FyjgI1vQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_r6fP51GfQgG_x89x4ZkCg.png" /></figure><p>after these steps will get access key and Secret access key save it because you will not get it again else need to create again.</p><blockquote><strong>Coding</strong></blockquote><p>In this i will be using echo framework and doing in clear architecture</p><p>i will give my project structure below.If you only want the code for s3 you can directly refer the <strong>s3service.go </strong>file in<strong> client </strong>directory.</p><pre>├── cmd<br>│   └── main.go<br>├── go.mod<br>├── go.sum<br>└── pkg<br>    ├── boot<br>    │   └── server.go<br>    ├── client<br>    │   └── s3service.go<br>    ├── config<br>    │   └── config.go<br>    ├── di<br>    │   └── di.go<br>    ├── routes<br>    │   └── userroutes.go<br>    └── user<br>        ├── handler<br>        │   └── handle.go<br>        └── service<br>            └── service.go</pre><p>firstly we will create the .env file</p><pre><br>HOST=0.0.0.0<br>SERVER_PORT=8080<br>AccesKey=&quot;your AccesKey&quot;<br>SecretKey=&quot;your SecretKey&quot;</pre><blockquote><strong><em>config.go</em></strong></blockquote><pre>package config<br><br>import (<br> &quot;github.com/go-playground/validator&quot;<br> &quot;github.com/spf13/viper&quot;<br>)<br><br>type Config struct {<br> AccesKey  string `mapstructure:&quot;AccesKey&quot;`<br> SecretKey string `mapstructure:&quot;SecretKey&quot;`<br><br> Host       string `mapstructure:&quot;HOST&quot;`<br> ServerPort string `mapstructure:&quot;SERVER_PORT&quot;`<br>}<br><br>var envs = []string{<br> &quot;AccesKey&quot;, &quot;SecretKey&quot;, &quot;HOST&quot;, &quot;SERVER_PORT&quot;,<br>}<br><br>func LoadConfig() (Config, error) {<br> var config Config<br><br> viper.SetConfigFile(&quot;./pkg/config/.env&quot;)<br> viper.ReadInConfig()<br><br> for _, env := range envs {<br>  if err := viper.BindEnv(env); err != nil {<br>   return config, err<br>  }<br> }<br><br> if err := viper.Unmarshal(&amp;config); err != nil {<br>  return config, err<br> }<br><br> if err := validator.New().Struct(&amp;config); err != nil {<br>  return config, err<br> }<br><br> return config, nil<br>}</pre><blockquote><strong>Userroutes.go</strong></blockquote><pre>package routes<br><br>import (<br> &quot;s3service/pkg/boot&quot;<br> &quot;s3service/pkg/user/handler&quot;<br>)<br><br>type UserRoutesstruct struct {<br> Server *boot.Server<br> User   handler.Handler<br>}<br><br>func (ur *UserRoutesstruct) Routes() {<br><br> ur.Server.Engine.POST(&quot;/upload&quot;, ur.User.Upload)<br> ur.Server.Engine.GET(&quot;/Image/:name&quot;, ur.User.Retrive)<br><br>}</pre><blockquote><strong>Handler.go</strong></blockquote><pre>package handler<br><br>import (<br> &quot;fmt&quot;<br> &quot;net/http&quot;<br> &quot;reflect&quot;<br> &quot;s3service/pkg/user/service&quot;<br><br> &quot;github.com/labstack/echo&quot;<br>)<br><br>type Handler struct {<br> Service service.Service<br>}<br>type UserHandler interface {<br> Upload(c echo.Context) error<br> Retrive(c echo.Context) error<br>}<br><br>func (h *Handler) Upload(c echo.Context) error {<br> file, _ := c.FormFile(&quot;file&quot;)<br> fmt.Println(&quot;file  ....&quot;, file)<br> fmt.Println(&quot;Type of x:&quot;, reflect.TypeOf(file))<br> src, err := file.Open()<br> if err != nil {<br>  return c.JSON(http.StatusInternalServerError, map[string]string{&quot;error&quot;: err.Error()})<br> }<br> defer src.Close()<br><br> err = h.Service.Upload(src, file)<br> if err != nil {<br>  return c.JSON(http.StatusInternalServerError, map[string]string{&quot;error&quot;: err.Error()})<br> }<br> return c.String(http.StatusOK, &quot;File uploaded successfully&quot;)<br><br>}<br>func (h *Handler) Retrive(c echo.Context) error {<br> name := c.Param(&quot;name&quot;)<br> url, err := h.Service.Retrive(name)<br> if err != nil {<br>  return c.JSON(http.StatusInternalServerError, map[string]string{&quot;error&quot;: err.Error()})<br><br> }<br><br> return c.String(http.StatusOK, url)<br><br>}</pre><blockquote><strong>Service.go</strong></blockquote><pre>package service<br><br>import (<br> &quot;bytes&quot;<br><br> &quot;io&quot;<br> &quot;mime/multipart&quot;<br> &quot;s3service/pkg/client&quot;<br>)<br><br>type serviceInt interface {<br> Upload(file multipart.File, head *multipart.FileHeader) error<br> Retrive(file string) (string, error)<br>}<br>type Service struct {<br> S3 client.S3pathway<br>}<br><br>func (s *Service) Retrive(file string) (string, error) {<br> url, err := s.S3.RetriveFile(file)<br> if err != nil {<br>  return &quot;&quot;, err<br><br> }<br> return url, nil<br>}<br><br>func (s *Service) Upload(file multipart.File, head *multipart.FileHeader) error {<br><br> filebyte, err := convertToByte(file)<br> if err != nil {<br>  return err<br> }<br><br> err = s.S3.UploadFile(filebyte, head.Filename)<br> if err != nil {<br><br>  return err<br> }<br> return nil<br>}<br><br>func convertToByte(file multipart.File) ([]byte, error) {<br> var buf bytes.Buffer<br> _, err := io.Copy(&amp;buf, file)<br> if err != nil {<br>  return nil, err<br> }<br> return buf.Bytes(), nil<br><br>}</pre><blockquote><strong>S3service.go</strong></blockquote><pre>package client<br><br>import (<br> &quot;bytes&quot;<br> &quot;context&quot;<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;time&quot;<br><br> &quot;s3service/pkg/config&quot;<br><br> &quot;github.com/aws/aws-sdk-go-v2/aws&quot;<br> awsconf &quot;github.com/aws/aws-sdk-go-v2/config&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/credentials&quot;<br> &quot;github.com/aws/aws-sdk-go-v2/service/s3&quot;<br>)<br><br>var s3Client *s3.Client<br><br>type S3exposeGateway interface {<br> UploadFile(file []byte, key string) error<br> RetriveFile(file string) (string, error)<br> Init()<br>}<br><br>type S3pathway struct {<br> Conf config.Config<br>}<br><br>func (s *S3pathway) Init() {<br> awsCfg, err := awsconf.LoadDefaultConfig(context.TODO(),<br>  awsconf.WithRegion(&quot;us-east-2&quot;),<br>  awsconf.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(<br>   s.Conf.AccesKey, s.Conf.SecretKey, &quot;&quot;)),<br> )<br><br> if err != nil {<br>  log.Fatalf(&quot;unable to load SDK config, %v&quot;, err)<br> }<br><br> s3Client = s3.NewFromConfig(awsCfg)<br>}<br>func (s *S3pathway) UploadFile(file []byte, key string) error {<br> bucketName := s.Conf.BucketName<br><br> _, err := s3Client.PutObject(context.TODO(), &amp;s3.PutObjectInput{<br>  Bucket: aws.String(bucketName),<br>  Key:    aws.String(key),<br>  Body:   bytes.NewReader(file),<br><br>  ContentLength: aws.Int64(int64(len(file))),<br>  ContentType:   aws.String(&quot;application/octet-stream&quot;),<br> })<br> if err != nil {<br>  return err<br> }<br> fmt.Println(&quot;wnded the service&quot;)<br> return nil<br>}<br>func (s *S3pathway) RetriveFile(file string) (string, error) {<br> presigner := s3.NewPresignClient(s3Client)<br> bucketName := s.Conf.BucketName<br> req, err := presigner.PresignGetObject(context.TODO(), &amp;s3.GetObjectInput{<br>  Bucket:                     aws.String(bucketName),<br>  Key:                        aws.String(file),<br>  ResponseContentDisposition: aws.String(&quot;inline&quot;),<br> }, s3.WithPresignExpires(15*time.Minute))<br> if err != nil {<br>  return &quot;&quot;, err<br><br> }<br> return req.URL, nil<br>}</pre><blockquote><strong>Di.go</strong></blockquote><pre>package di<br><br>import (<br> &quot;s3service/pkg/boot&quot;<br> &quot;s3service/pkg/client&quot;<br> &quot;s3service/pkg/config&quot;<br> &quot;s3service/pkg/routes&quot;<br> &quot;s3service/pkg/user/handler&quot;<br> &quot;s3service/pkg/user/service&quot;<br>)<br><br><br>func Init(cnf config.Config) *boot.Server {<br><br> s3initializer := client.S3pathway{Conf: cnf}<br> s3initializer.Init()<br><br> server := boot.NewHTTPServer()<br> service := service.Service{<br>  S3: s3initializer,<br> }<br> handler := handler.Handler{<br>  Service: service,<br> }<br> usRoute := routes.UserRoutesstruct{<br>  Server: server,<br>  User:   handler,<br> }<br> usRoute.Routes()<br><br> return server<br><br>}</pre><blockquote><strong>server.go</strong></blockquote><pre>package boot<br><br>import &quot;github.com/labstack/echo&quot;<br><br>type Server struct {<br> Engine *echo.Echo<br>}<br><br>func (s *Server) Start() {<br> s.Engine.Start(&quot;localhost:8080&quot;)<br>}<br><br>func NewHTTPServer() *Server {<br> e := echo.New()<br> return &amp;Server{<br>  Engine: e,<br> }<br>}</pre><blockquote><strong>main.go</strong></blockquote><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;s3service/pkg/config&quot;<br> &quot;s3service/pkg/di&quot;<br>)<br><br>func main() {<br> cnf, err := config.LoadConfig()<br><br> if err != nil {<br>  log.Fatal(&quot;failed to load environements&quot;)<br> }<br> server := di.Init(cnf)<br> server.Start()<br>}</pre><blockquote><strong>Testing</strong></blockquote><p>ok now we can see the testing in postman.Firstly we will start with upload.</p><blockquote><strong>Upload</strong></blockquote><p><strong>url </strong>— <a href="http://localhost:8080/upload">http://localhost:8080/upload</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9498driumVaSPytOZXX8Zg.png" /></figure><p>now lets see in the <strong>s3 bucket</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWvOz0cuLH3gsSMAtcQj4Q.png" /></figure><blockquote><strong>Retrive</strong></blockquote><p>In this we will get a <strong>presigned url </strong>that is valid only for a certain time period.</p><p><strong>url</strong>- <a href="http://localhost:8080/Image/Ankit.pdf">http://localhost:8080/Image/Ankit.pdf</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SNuv_9HBSMOAU_lQtjV6vQ.png" /></figure><h3>Conclusion</h3><p><strong>Uploading</strong> and<strong> retrieving</strong> files from an <strong>AWS S3 bucket</strong> using <strong>Go</strong> is a critical functionality for building scalable, cloud-native applications. By leveraging the <strong>AWS SDK for Go</strong>, you can seamlessly manage file storage and access with minimal effort. Whether you&#39;re building an e-commerce platform or any data-driven application, integrating S3 offers you flexibility, reliability, and cost-effective storage. If you&#39;d like to explore the complete codebase or contribute to the project, check out my for detailed implementation and examples.</p><blockquote><em>You can find the repository here: </em><a href="https://github.com/adi-dev-x/uploading-and-retriving-files-in-aws-s3-bucket-using-go"><strong>Uploading and retrieving files from an AWS S3 bucket</strong><em>.</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec006ef65cc3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Clean Architecture in Go: Tips & Examples]]></title>
            <link>https://medium.com/@adithyanunni258/clean-architecture-in-go-82372752e9f9?source=rss-e3f6af643d05------2</link>
            <guid isPermaLink="false">https://medium.com/p/82372752e9f9</guid>
            <dc:creator><![CDATA[Adithyanunni]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 11:43:38 GMT</pubDate>
            <atom:updated>2024-09-05T04:55:18.850Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*uoKXOJVHPmh4fH76CnT_ew.png" /></figure><p>In modern software development, <strong>creating scalable and maintainable architecture</strong> is crucial for long-term success. One popular approach is <strong>Clean Architecture</strong>, known for <strong>separating concerns</strong>, enhancing <strong>code maintainability</strong>, and improving <strong>testability</strong>. In this post, we’ll explore how to implement <strong>Clean Architecture in GoLang (Go)</strong> and walk you through the fundamental concepts with real-world examples. Follow the guide to learn best practices and streamline your development process. You can also find a link to my <strong>GoLang Clean Architecture repository</strong> below for reference.</p><p><strong>What is Clean Architecture?</strong></p><p><strong>Clean Architecture</strong>, introduced by <strong>Robert C. Martin (Uncle Bob)</strong>, is a robust <strong>software design pattern</strong> that emphasizes the <strong>separation of concerns</strong>, enhancing <strong>system maintainability</strong>, <strong>scalability</strong>, and <strong>testability</strong>. By decoupling the <strong>core business logic</strong> from external elements like <strong>databases</strong> or <strong>user interfaces (UI)</strong>, this approach allows developers to implement changes without affecting the entire system.</p><p>In my implementation of <strong>Clean Architecture in GoLang</strong>, I structure the application with three essential layers:</p><ol><li><strong>Handler Layer</strong>: Handles API routing using the <strong>Echo framework</strong>.</li><li><strong>Service Layer</strong>: Manages the core business logic and its implementation.</li><li><strong>Repository/Data Layer</strong>: Oversees database interactions using <strong>SQL with GORM</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gac2B2DDqOBIB1bBTbhang.png" /></figure><p>This is the basic representation of <strong>Clean Architecture</strong> where each layer is independent of the others, allowing them to be <strong>replaced without disturbing</strong> the other layers. Let’s start with the <strong>Handler Layer</strong>.</p><h3>Handler Layer (API and Route Management)</h3><p>The <strong>Handler layer</strong> is responsible for <strong>processing HTTP requests</strong> and routing them to the appropriate services. It acts as the entry point of the system, managing <strong>API endpoints</strong> and controlling the flow of data into the application.</p><h4>Key Responsibilities:</h4><ul><li>Define and set up routes for various API endpoints.</li><li>Parse incoming requests and validate the inputs.</li><li>Forward valid requests to the <strong>Service Layer</strong> for processing.</li><li>Send responses back to the client, typically in <strong>JSON</strong> or <strong>XML</strong> format.</li></ul><p>This layer is kept lightweight, focusing solely on <strong>communication between the client and backend</strong>. It contains no business logic and ensures that the routing and request handling remain clear and easy to manage.</p><h3>Service Layer (Business Logic and Implementation)</h3><p>The <strong>Service Layer</strong> is the heart of the application, where the <strong>core business logic</strong> resides. This layer serves as a bridge between the <strong>Handler</strong> and <strong>Repository</strong> layers, processing the main functionality of the system.</p><h4>Key Responsibilities:</h4><ul><li>Manage <strong>business rules</strong> and handle application logic.</li><li>Implement workflows, complex <strong>calculations</strong>, and data <strong>validations</strong>.</li><li>Process data received from the <strong>Repository Layer</strong> (database).</li><li>Return processed results to the <strong>Handler Layer</strong> for a client-facing response.</li></ul><p>By centralizing the business logic here, the <strong>Service Layer</strong> ensures that all rules are <strong>isolated</strong> and can be easily tested or modified. This isolation allows for flexibility, enabling changes to business logic without affecting the <strong>UI</strong> or <strong>database interactions</strong>.</p><p>Here’s an SEO-optimized version of your content for the <strong>Repository/Data Layer</strong>:</p><h3>Repository/Data Layer (Database Interaction)</h3><p>The <strong>Repository/Data Layer</strong> is responsible for managing direct interactions with the <strong>database</strong> and handling data persistence. This layer abstracts database operations from the rest of the application, ensuring that changes to the database or its structure do not affect other parts of the codebase.</p><h4>Key Responsibilities:</h4><ul><li><strong>Query</strong> the database to <strong>fetch data</strong> for the application.</li><li><strong>Insert</strong>, <strong>update</strong>, or <strong>delete records</strong> as required.</li><li>Map database models to <strong>Go structs</strong> or entities.</li><li>Provide <strong>consistent data</strong> to the <strong>Service Layer</strong> for processing.</li></ul><p>In this implementation, <strong>SQL</strong> is used for database interactions, and <strong>GORM</strong> handles the mapping and queries. Decoupling the <strong>Repository Layer</strong> from the <strong>business logic</strong> simplifies future changes or database migrations, allowing the system to remain flexible and scalable.</p><h3><strong>Coding!!</strong></h3><p>I will implement each layers ,i will be using here <strong>Echo</strong> framework</p><p><strong>Folder Structure-</strong></p><pre>├── cmd<br>│   └── usermanagement<br>│       └── main.go<br>├── go.mod<br>├── go.sum<br>└── internal<br>    ├── config<br>    │   └── config.go<br>    ├── database<br>    │   └── db.go<br>    ├── di<br>    │   └── di.go<br>    ├── routes<br>    │   └── userRoutes.go<br>    ├── server<br>    │   └── server.go<br>    └── user<br>        ├── delivery<br>        │   └── user_handler.go<br>        ├── entity<br>        │   └── user.go<br>        ├── repository<br>        │   └── user_repository.go<br>        └── usecase<br>            └── user_usecase.go<br><br>14 directories, 12 files</pre><blockquote><strong><em>main.go</em></strong></blockquote><pre>package main<br><br>import (<br> &quot;basiccrud/internal/config&quot;<br> &quot;basiccrud/internal/di&quot;<br> &quot;log&quot;<br>)<br><br>func main() {<br> cnf, err := config.LoadConfig()<br> if err != nil {<br>  log.Fatal(&quot;failed to load environments&quot;)<br> }<br> server := di.Init(cnf)<br> server.StartServer()<br>}</pre><blockquote><strong>server.go</strong></blockquote><pre>package server<br><br>import &quot;github.com/labstack/echo&quot;<br><br>type ServerStruct struct {<br> Engine *echo.Echo<br>}<br><br>func (s *ServerStruct) StartServer() {<br> s.Engine.Start(&quot;localhost:8080&quot;)<br>}<br><br>func NewHTTPServer() *ServerStruct {<br> e := echo.New()<br><br> return &amp;ServerStruct{<br>  Engine: e,<br> }<br>}</pre><blockquote><strong><em>config.go</em></strong></blockquote><pre>package config<br><br>import (<br> &quot;github.com/go-playground/validator/v10&quot;<br> &quot;github.com/spf13/viper&quot;<br>)<br><br>type Config struct {<br> PGUserName   string `mapstructure:&quot;PG_USERNAME&quot;`<br> PGPassword   string `mapstructure:&quot;PG_PASSWORD&quot;`<br> PgSSLMode    string `mapstructure:&quot;PG_SSL_MODE&quot;`<br> PGDBmsName   string `mapstructure:&quot;PG_DBMS_NAME&quot;`<br> PGHost       string `mapstructure:&quot;PG_HOST&quot;`<br> PgDriverName string `mapstructure:&quot;PG_DRIVER_NAME&quot;`<br> PGDBName     string `mapstructure:&quot;PG_DB_NAME&quot;`<br> PgPort       string `mapstructure:&quot;PG_PORT&quot;`<br><br> Host       string `mapstructure:&quot;HOST&quot;`<br> ServerPort string `mapstructure:&quot;SERVER_PORT&quot;`<br>}<br><br>var envs = []string{<br> &quot;PG_USERNAME&quot;, &quot;PG_PASSWORD&quot;, &quot;PG_SSL_MODE&quot;, &quot;PG_DBMS_NAME&quot;, &quot;PG_HOST&quot;,<br> &quot;PG_DRIVER_NAME&quot;, &quot;PG_DB_NAME&quot;, &quot;PG_PORT&quot;, &quot;HOST&quot;, &quot;SERVER_PORT&quot;,<br>}<br><br>func LoadConfig() (Config, error) {<br> var config Config<br><br> viper.SetConfigFile(&quot;./pkg/config/.env&quot;)<br> viper.ReadInConfig()<br><br> for _, env := range envs {<br>  if err := viper.BindEnv(env); err != nil {<br>   return config, err<br>  }<br> }<br><br> if err := viper.Unmarshal(&amp;config); err != nil {<br>  return config, err<br> }<br><br> if err := validator.New().Struct(&amp;config); err != nil {<br>  return config, err<br> }<br><br> return config, nil<br>}</pre><p>.env</p><pre>PG_USERNAME=postgres<br>PG_PASSWORD=your password<br>PG_HOST=localhost<br>PG_PORT=5432(default port)<br>PG_DB_NAME=your db name<br>PG_SSL_MODE=disable(default)<br>PG_DRIVER_NAME=postgres(default)<br>PG_DBMS_NAME=postgres(default)<br><br><br><br>HOST=0.0.0.0<br>SERVER_PORT=8080</pre><blockquote><strong><em>di.go</em></strong></blockquote><pre>package di<br><br>import (<br> &quot;basiccrud/internal/config&quot;<br> &quot;basiccrud/internal/database&quot;<br> &quot;basiccrud/internal/routes&quot;<br> &quot;basiccrud/internal/server&quot;<br> &quot;basiccrud/internal/user/delivery&quot;<br> &quot;basiccrud/internal/user/repository&quot;<br> &quot;basiccrud/internal/user/usecase&quot;<br>)<br><br>func Init(conf config.Config) *server.ServerStruct {<br> server := server.NewHTTPServer()<br> db := db.ConnectPGDB(conf)<br> repo := repository.NewUserRepository(db)<br> usecase := usecase.UseCase(repo)<br> delivery := delivery.UserDelivery(usecase)<br> userRoutes := routes.NewUserInit(server, delivery)<br> userRoutes.UserRoutes()<br> return server<br>}</pre><blockquote><strong>userRoutes.go</strong></blockquote><pre>package routes<br><br>import (<br> &quot;basiccrud/internal/server&quot;<br> &quot;basiccrud/internal/user/delivery&quot;<br>)<br><br>type UserRoutesstruct struct {<br> Server *server.ServerStruct<br> User   delivery.UserUserCase<br>}<br><br>func (u *UserRoutesstruct) UserRoutes() {<br><br> u.Server.Engine.POST(&quot;/signup&quot;, u.User.RegisterUserHandler)<br> u.Server.Engine.POST(&quot;/login&quot;, u.User.LoginUserHandler)<br>}<br><br>func NewUserInit(server *server.ServerStruct, user delivery.UserUserCase) *UserRoutesstruct {<br> return &amp;UserRoutesstruct{<br>  Server: server,<br>  User:   user,<br> }<br>}</pre><blockquote><strong><em>user_handle.go</em></strong></blockquote><pre>package delivery<br><br>import (<br> user &quot;basiccrud/internal/user/entity&quot;<br> &quot;basiccrud/internal/user/usecase&quot;<br> &quot;net/http&quot;<br><br> &quot;github.com/labstack/echo&quot;<br>)<br><br>type UserHandler struct {<br> userUseCase usecase.UserUseCase<br>}<br><br>type UserUserCase interface {<br> RegisterUserHandler(c echo.Context) error <br> LoginUserHandler(c echo.Context) error <br>}<br><br>func (u *UserHandler) RegisterUserHandler(c echo.Context) error {<br> var user user.UserRegister<br> if err := c.Bind(&amp;user); err != nil {<br><br>  return c.JSON(http.StatusBadRequest, map[string]string{<br>   &quot;error&quot;: &quot;bad request&quot;,<br>  })<br><br> }<br> ctx := c.Request().Context()<br> if err := u.userUseCase.RegisterUser(ctx, &amp;user); err != nil {<br>  return c.JSON(http.StatusBadRequest, map[string]string{<br>   &quot;error&quot;: &quot;error in the data&quot;,<br>  })<br><br> }<br><br> return c.JSON(http.StatusOK, map[string]string{<br>  &quot;Message&quot;: &quot;created&quot;,<br> })<br><br>}<br><br>func (u *UserHandler) LoginUserHandler(c echo.Context) error {<br> var userLogin user.UserLogin<br> if err := c.Bind(&amp;userLogin); err != nil {<br><br>  return c.JSON(400, map[string]string{&quot;Error&quot;: &quot;binding error&quot;})<br><br> }<br><br> user, err := u.userUseCase.Login(&amp;userLogin)<br> if err != nil {<br>  return c.JSON(500, map[string]string{&quot;Error&quot;: err.Error()})<br><br> }<br> response := map[string]interface{}{<br>  &quot;data&quot;: user,<br> }<br> return c.JSON(200, response)<br>}<br><br>func UserDelivery(userUseCase usecase.UserUseCase) UserUserCase {<br> return &amp;UserHandler{<br>  userUseCase: userUseCase,<br> }<br>}</pre><blockquote><strong>user.go</strong></blockquote><pre>package user<br><br>import &quot;gorm.io/gorm&quot;<br><br>type UserRegister struct {<br> gorm.Model<br> Username string `json:&quot;username&quot; gorm:&quot;not null;unique&quot;`<br> Name     string `json:&quot;name&quot; gorm:&quot;not null;unique&quot;`<br> Email    string `json:&quot;email&quot; gorm:&quot;not null;unique&quot;`<br> Phone    string `json:&quot;phone&quot; gorm:&quot;not null;unique&quot;`<br> Password string `json:&quot;password&quot; gorm:&quot;not null&quot;`<br>}<br><br>type UserLogin struct {<br> Username string `json:&quot;username&quot;`<br> Password string `json:&quot;password&quot;`<br>}</pre><blockquote><strong>user_repository.go</strong></blockquote><pre>package repository<br><br>import (<br> user &quot;basiccrud/internal/user/entity&quot;<br><br> &quot;gorm.io/gorm&quot;<br>)<br><br>type UserRepository interface {<br> CreateUser(user *user.UserRegister) error<br> FindUserByUserName(username string) (*user.UserRegister, error)<br>}<br><br>type UserDataBaseInteraction struct {<br> DB *gorm.DB<br>}<br><br>func (u *UserDataBaseInteraction) CreateUser(user *user.UserRegister) error {<br> result := u.DB.Create(&amp;user)<br> if result.Error != nil {<br>  return result.Error<br> }<br> return nil<br>}<br><br>func (u *UserDataBaseInteraction) FindUserByUserName(username string) (*user.UserRegister, error) {<br> var user *user.UserRegister<br> if err := u.DB.Where(&quot;userrname = ?&quot;, username).First(&amp;user).Error; err != nil {<br>  return nil, err<br> }<br> return user, nil<br>}<br><br>func NewUserRepository(db *gorm.DB) UserRepository {<br> return &amp;UserDataBaseInteraction{<br>  DB: db,<br> }<br>}</pre><blockquote><strong>user_usercase.go</strong></blockquote><pre>package usecase<br><br>import (<br> user &quot;basiccrud/internal/user/entity&quot;<br> &quot;basiccrud/internal/user/repository&quot;<br> &quot;context&quot;<br> &quot;errors&quot;<br>)<br><br>type UserUseCase interface {<br> RegisterUser(ctx context.Context, user *user.UserRegister) error<br> Login(login *user.UserLogin) (*user.UserRegister, error)<br>}<br><br>type UserInteraction struct {<br> UserRepository repository.UserRepository<br>}<br><br>func (u *UserInteraction) RegisterUser(ctx context.Context, user *user.UserRegister) error {<br> if len(user.Phone) &lt; 10 {<br>  return errors.New(&quot;username must be atleast 3 characters long&quot;)<br> }<br><br> err := u.UserRepository.CreateUser(user)<br> if err != nil {<br>  return err<br> }<br><br> return nil<br>}<br><br>func (u *UserInteraction) Login(login *user.UserLogin) (*user.UserRegister, error) {<br> user, err := u.UserRepository.FindUserByUserName(login.Username)<br> if err != nil {<br>  return nil, err<br> }<br> if login.Password != user.Password {<br>  return nil, errors.New(&quot;password error&quot;)<br> }<br> return user, nil<br>}<br><br>func UseCase(repo repository.UserRepository) UserUseCase {<br> return &amp;UserInteraction{<br>  UserRepository: repo,<br> }<br>}</pre><h3>Conclusion</h3><p>In this <strong>Medium post</strong>, we’ve explored the implementation of <strong>Clean Architecture</strong> in a <strong>GoLang application</strong> using the <strong>Echo framework</strong> and <strong>GORM</strong> with a <strong>PostgreSQL</strong> database. This approach ensures a <strong>scalable</strong> and <strong>maintainable structure</strong>, ideal for building robust applications.</p><p>We covered key aspects such as implementing <strong>user registration</strong> and <strong>login APIs</strong>, showcasing how following <strong>Clean Architecture principles</strong> keeps the codebase organized, easy to maintain, and extendable.</p><p>For a hands-on experience, you can check out the full project on <strong>GitHub</strong>. Feel free to <strong>clone the repository</strong>, review the code, and contribute with improvements or suggestions.</p><blockquote>You can find the repository here: <a href="https://github.com/adi-dev-x/Basic-Crud-for-clean-architecture-in-GO"><strong>Basic CRUD for Clean Architecture in Go</strong></a>.</blockquote><p><strong>Thank you for reading!</strong> I hope this guide helps you on your journey with <strong>Clean Architecture in GoLang</strong>. Feel free to explore the concepts further and apply them to your own projects for building maintainable and scalable applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82372752e9f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>