<?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 Nikolay Benlioglu on Medium]]></title>
        <description><![CDATA[Stories by Nikolay Benlioglu on Medium]]></description>
        <link>https://medium.com/@nbenliogludev?source=rss-796737a1c483------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XFbJ1YfXS_7SiSGWwMuuDw.jpeg</url>
            <title>Stories by Nikolay Benlioglu on Medium</title>
            <link>https://medium.com/@nbenliogludev?source=rss-796737a1c483------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 17:07:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nbenliogludev/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[ Builder Design Pattern: Sade Anlatım + Kod Örnekleri]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nbenliogludev/builder-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-83e8a0023811?source=rss-796737a1c483------2"><img src="https://cdn-images-1.medium.com/max/1536/1*gmdmdJQlKcb7V0QWJowf8w.png" width="1536"></a></p><p class="medium-feed-snippet">&#x130;leri d&#xFC;zey yaz&#x131;l&#x131;m projelerinde, baz&#x131; s&#x131;n&#x131;flar &#xE7;ok say&#x131;da parametreyle &#xE7;al&#x131;&#x15F;&#x131;r; bunlar&#x131;n bir k&#x131;sm&#x131; zorunlu, bir k&#x131;sm&#x131; iste&#x11F;e ba&#x11F;l&#x131;d&#x131;r&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@nbenliogludev/builder-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-83e8a0023811?source=rss-796737a1c483------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nbenliogludev/builder-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-83e8a0023811?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/83e8a0023811</guid>
            <category><![CDATA[builder-pattern]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[builder-design-pattern]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Sun, 27 Apr 2025 15:44:27 GMT</pubDate>
            <atom:updated>2025-04-27T15:44:27.640Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ Facatory Design Pattern: Sade Anlatım + Kod Örnekleri]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nbenliogludev/facatory-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-d19d65d616e8?source=rss-796737a1c483------2"><img src="https://cdn-images-1.medium.com/max/929/1*LBEVg4DbLQUrv1EQsk6rVQ.png" width="929"></a></p><p class="medium-feed-snippet">Factory Method, varolu&#x15F;sal (Creational) bir tasar&#x131;m desenidir.</p><p class="medium-feed-link"><a href="https://medium.com/@nbenliogludev/facatory-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-d19d65d616e8?source=rss-796737a1c483------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nbenliogludev/facatory-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-d19d65d616e8?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/d19d65d616e8</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Fri, 25 Apr 2025 21:55:24 GMT</pubDate>
            <atom:updated>2025-04-25T21:56:05.138Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ Singleton Design Pattern: Sade Anlatım + Kod Örnekleri]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@nbenliogludev/singleton-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-abf3f56bdf28?source=rss-796737a1c483------2"><img src="https://cdn-images-1.medium.com/max/1110/0*thP5FvrHbNbvVuD9.png" width="1110"></a></p><p class="medium-feed-snippet">Singleton</p><p class="medium-feed-link"><a href="https://medium.com/@nbenliogludev/singleton-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-abf3f56bdf28?source=rss-796737a1c483------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@nbenliogludev/singleton-design-pattern-sade-anlat%C4%B1m-kod-%C3%B6rnekleri-abf3f56bdf28?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/abf3f56bdf28</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Tue, 22 Apr 2025 21:11:25 GMT</pubDate>
            <atom:updated>2025-04-22T21:29:26.818Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Spring Boot’ta Yaygın Olarak Kullanılan Temel Anotasyonlar: Tanımları ve Uygulama Örnekleri]]></title>
            <link>https://medium.com/@nbenliogludev/spring-bootta-yayg%C4%B1n-olarak-kullan%C4%B1lan-temel-anotasyonlar-tan%C4%B1mlar%C4%B1-ve-uygulama-%C3%B6rnekleri-f69d39050081?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/f69d39050081</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[beans]]></category>
            <category><![CDATA[autowired]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[annotations]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 13:30:32 GMT</pubDate>
            <atom:updated>2025-04-21T23:39:56.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_LXS4yKDubQlLDyFDUHVBA.png" /></figure><h3>1. @SpringBootApplication</h3><p>@SpringBootApplication anotasyonu, Spring Boot uygulamalarının başlangıç noktasıdır ve üç önemli anotasyonu birleştirir: @Configuration, @EnableAutoConfiguration ve @ComponentScan. Genellikle ana sınıfa yazılır ve uygulamanın otomatik yapılandırılmasını sağlar.</p><pre>package com.example.demo;<br><br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication  // @Configuration + @EnableAutoConfiguration + @ComponentScan<br>public class DemoApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(DemoApplication.class, args);<br>    }<br>}</pre><h3>2. @Bean</h3><p>@Bean anotasyonu, Spring uygulamalarında bir metot aracılığıyla özel olarak oluşturulan nesnelerin (bean&#39;lerin) Spring konteynerine manuel olarak kaydedilmesini sağlar. Bu sayede geliştiriciler, dış kütüphanelerden gelen ya da @Component ile işaretlenemeyen sınıfları da Spring tarafından yönetilen nesneler haline getirebilir. Genellikle @Configuration sınıfı içinde tanımlanır ve singleton olarak çalışır.</p><pre>@Configuration<br>public class AppConfig {<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder(); // Bu bean, singleton olarak context&#39;e eklenir<br>    }<br>}</pre><h3>3. @Service</h3><p>@Service, Spring Framework’te bir sınıfın <strong>iş mantığı (business logic)</strong> içerdiğini belirtmek için kullanılan bir anotasyondur. Spring, bu anotasyonu gördüğünde ilgili sınıfı bir <strong>bean</strong> olarak kaydeder ve yönetmeye başlar.</p><pre>@Service<br>public class UserService {<br><br>    public String getWelcomeMessage() {<br>        return &quot;Welcome to the User Service!&quot;;<br>    }<br>}</pre><h3>4. @Configuration</h3><p>@Configuration anotasyonu, sınıf tabanlı bir anotasyondur ve içinde bir veya daha fazla @Bean metodunu tanımlamak için kullanılır. Bu sınıf, servisler ve diğer uygulama bileşenleri gibi yapıların Spring uygulama bağlamına (application context) ekleneceğini belirtir.</p><pre>@Configuration<br>public class AppConfig {<br><br>    @Bean<br>    public PasswordEncoder passwordEncoder() {<br>        return new BCryptPasswordEncoder();<br>    }<br>}</pre><pre>// @Service anotasyonu sayesinde Spring, bu sınıfı otomatik olarak <br>// bir bean olarak tanır ve IoC konteynerine ekler.<br>@Service<br>public class UserService {<br><br>    // PasswordEncoder bağımlılığı constructor üzerinden enjekte edilir.<br>    // Spring, uygulama başlatılırken PasswordEncoder bean&#39;ini bulur ve <br>    // otomatik olarak buraya enjekte eder.<br>    private final PasswordEncoder passwordEncoder;<br><br>    // Constructor Injection yöntemi kullanılmıştır.<br>    public UserService(PasswordEncoder passwordEncoder) {<br>        this.passwordEncoder = passwordEncoder;<br>    }<br><br>    public void registerUser(String rawPassword) {<br>        String encodedPassword = passwordEncoder.encode(rawPassword);<br>    }<br>}</pre><h3>5. @Autowired</h3><p>Spring Boot’ta kullanılan @Autowired anotasyonu, bir bean’in bağımlılığını başka bir bean’e enjekte etmek için kullanılır. Spring tarafından yönetilen bir nesne, ihtiyaç duyan başka bir nesneye otomatik olarak entegre edilir.</p><p>Yani, bir alanı (field), metodu veya yapıcı metodu (constructor) @Autowired ile işaretlediğinizde, Spring Boot bu bağımlılığı otomatik olarak enjekte eder ve o alana uygun olan bean’i bulur.</p><p>@Autowired üç şekilde kullanılabilir: field enjeksiyonu, setter enjeksiyonu ve constructor enjeksiyonu.</p><p>Başka bir deyişle, Spring Boot’ta @Autowired anotasyonu, bir nesnenin yaşam döngüsünün tamamını yönetir.</p><pre>// @Service sayesinde Spring tarafından otomatik olarak bean olarak <br>// Tanınır ve IoC konteynerine eklenir.<br>@Service<br>public class UserService {<br><br>    // Field Injection kullanılmıştır.<br>    // @Autowired ile Spring, uygun tipteki bean&#39;i (UserRepository)<br>    // Otomatik olarak buraya enjekte eder.<br>    // Bu yöntem kolay olsa da test edilebilirlik ve değiştirilebilirlik <br>    // Açısından constructor injection kadar esnek değildir.<br>    @Autowired<br>    private UserRepository userRepository;<br><br>    public void doSomething() {<br>        userRepository.findAll(); // Repository katmanına erişim sağlanır<br>    }<br>}</pre><h3>6. @Component</h3><p>@Component anotasyonu, Spring uygulamalarında bir Java sınıfını işaretlemek için kullanılır. Spring’in IoC (Inversion of Control) konteyneri, bu anotasyonla işaretlenen sınıfları yönetir ve bu bileşenlerin yaşam döngüsünden (oluşturma, başlatma, yok etme gibi) sorumludur.</p><p>Bu sayede bileşenler, uygulama içindeki servisler, controller’lar veya başka nesneler olabilir. Bir sınıf @Component ile işaretlendiğinde, Spring Boot classpath taraması sayesinde bu bileşeni otomatik olarak algılar.</p><p>Ayrıca, bileşenler genellikle @Autowired ve @Qualifier anotasyonlarıyla birlikte kullanılarak bağımlılıkların otomatik olarak enjekte edilmesini sağlar.</p><pre>@Component<br>public class MyComponent {<br><br>    public String getMessage() {<br>        return &quot;Merhaba, field injection örneğindesin!&quot;;<br>    }<br>}</pre><pre>@Service<br>public class MyService {<br><br>    @Autowired<br>    private MyComponent myComponent;  // Field injection burada<br><br>    public void printMessage() {<br>        System.out.println(myComponent.getMessage());<br>    }<br>}</pre><h3>7. @Entity</h3><p>@Entity, Spring Data JPA’da bir Java sınıfının <strong>veritabanında bir tabloyu temsil ettiğini</strong> belirtmek için kullanılır. Bu anotasyonla işaretlenen sınıf, <strong>JPA (Java Persistence API)</strong> tarafından yönetilir ve veritabanı işlemlerine uygun hale gelir.</p><pre>import jakarta.persistence.Entity;<br>import jakarta.persistence.Id;<br><br>@Entity<br>public class User {<br><br>    @Id<br>    private Long id;<br>    private String username;<br><br>    // Getter ve Setter&#39;lar<br>    public Long getId() {<br>        return id;<br>    }<br><br>    public void setId(Long id) {<br>        this.id = id;<br>    }<br><br>    public String getUsername() {<br>        return username;<br>    }<br><br>    public void setUsername(String username) {<br>        this.username = username;<br>    }<br>}</pre><h3>8. @Repository</h3><p>@Repository anotasyonu, NoSQL veritabanları ve ilişkisel (relational) veritabanları gibi farklı veritabanlarıyla etkileşim kurmak için kullanılır. Bir Java sınıfı @Repository ile işaretlendiğinde, Spring Boot bu sınıfı otomatik olarak algılar ve gerekli uygulama bağlamına (application context) ekler.</p><p>@Repository ile işaretlenen sınıf, veri erişim katmanının (data access layer) bir öğesidir ve veritabanıyla etkileşim sağlamak için bir API sunar. Bu sayede geliştirici daha az kod yazarak veri işlemlerini gerçekleştirebilir.</p><pre>@Repository<br>public interface UserRepository extends JpaRepository&lt;User, Long&gt; {<br>    User findByUsername(String username);<br>}</pre><h3>9. @RestController</h3><p>@RestController anotasyonu, @ResponseBody ve @Controller anotasyonlarının işlevlerini birleştirir. Bu anotasyon, XML, JSON ve diğer türlerde cevaplar dönen RESTful endpoint&#39;lerin oluşturulmasını kolaylaştırır.</p><p>Spring Boot’ta @RestController, yalnızca JSON değil, düz metin (plain text), görsel (image) veya PDF gibi içerik türlerine cevap vermek için de kullanılabilir. Ayrıca, Spring Boot varsayılan olarak HTTP yanıtını ayarlasa da, @RestController sayesinde yanıtlar özelleştirilebilir.</p><p>Bir sınıf @RestController ile işaretlendiğinde, o sınıftaki tüm request mapping metotlarında ayrıca @ResponseBody yazmaya gerek kalmaz.</p><pre>@RestController  // @Controller + @ResponseBody<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br><br>    @GetMapping(&quot;/hello&quot;)<br>    public String sayHello() {<br>        return &quot;Merhaba kullanıcı!&quot;;<br>    }<br>}</pre><h3>10. @RequestBody</h3><p><strong>@RequestBody</strong>, HTTP istek gövdesindeki verileri otomatik olarak bir Java nesnesine dönüştürüp controller metoduna bağlamak için kullanılır. Genellikle JSON, XML gibi formatlardaki verileri alırken kullanılır ve Spring bu verileri otomatik olarak serileştirir. Özellikle RESTful servislerde, gelen veriyi doğrudan nesneye maplemek için idealdir.</p><pre>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br><br>    @PostMapping(&quot;/create&quot;)<br>    public String createUser(@RequestBody User user) {<br>        return &quot;Kullanıcı oluşturuldu: &quot; + user.getName() + &quot; (&quot; + user.getEmail() + &quot;)&quot;;<br>    }<br>}</pre><h3>11. @PathVariable</h3><p><strong>@PathVariable</strong>, HTTP isteğindeki URI yolundaki dinamik parametreleri alıp controller metoduna aktarır. RESTful servislerde, değişken URL parçalarını kolayca işlemenizi sağlar ve genellikle @GetMapping gibi anotasyonlarla birlikte kullanılır. Bu sayede daha okunabilir ve esnek API uç noktaları oluşturulabilir.</p><pre>import org.springframework.web.bind.annotation.*;<br><br>@RestController<br>@RequestMapping(&quot;/api/users&quot;)<br>public class UserController {<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public String getUserById(@PathVariable Long id) {<br>        return &quot;Kullanıcı ID: &quot; + id;<br>    }<br>}</pre><h3>12. @EnableAutoConfiguration</h3><p>Bu anotasyon, Spring Boot uygulamalarınızın otomatik olarak yapılandırılmasını sağlar. @EnableAutoConfiguration anotasyonu, gerekli Spring bileşenlerini tanımlar ve yapılandırmaları otomatik olarak gerçekleştirir.</p><p>Otomatik yapılandırılan bean’ler classpath üzerinde bulunur ve bu sayede geliştiricilerin işleri kolaylaşır. Gerekli bean’ler classpath’ten algılanarak uygulamanın çalışması için otomatik olarak yapılandırılır. Spring Boot’ta @EnableAutoConfiguration anotasyonu, bulunduğu sınıfın varsayılan paketini dikkate alır.</p><p>Ayrıca, bazı sınıfların otomatik yapılandırmaya dahil edilmesini istemiyorsanız, Spring Boot bu sınıfları manuel olarak hariç tutmanıza da olanak tanır.</p><pre>@Configuration<br>@EnableAutoConfiguration  // Spring Boot bileşenlerini otomatik yapılandır<br>@ComponentScan            // Bileşenleri tara<br>public class DemoApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(DemoApplication.class, args);<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f69d39050081" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Basic Load Balancer with Dynamic Backends with Nginx + Lua.]]></title>
            <link>https://medium.com/@nbenliogludev/building-basic-load-balancer-with-dynamic-backends-with-nginx-lua-da5d3cc77b52?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/da5d3cc77b52</guid>
            <category><![CDATA[lua]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[nginx-proxy]]></category>
            <category><![CDATA[openresty]]></category>
            <category><![CDATA[nginx]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Sat, 27 May 2023 20:42:21 GMT</pubDate>
            <atom:updated>2023-05-27T20:42:21.465Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.nginx.com/"><strong>Nginx</strong></a> is a web server that can also be used as a reverse proxy, load balancer, mail proxy, and HTTP cache.</p><h3>Implementation</h3><p>The first thing we need to do is to install <a href="https://openresty.org/en/"><strong>OpenResty</strong></a>. OpenResty is a modified version of nginx with LuaJIT compiled in and many nginx options that can be controlled or modified via Lua. It is very commonly used in content delivery networks for it’s configurability.</p><p>Once installed, you should navigate to your browser and type <a href="http://localhost./">http://localhost.</a> If everything goes well, you will see the below screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*zeY_GdpUw8DniBQ5Q4a2AA.png" /></figure><p>With this, you have successfully installed OpenResty along with Nginx.</p><p>Now, we need to edit the <strong>nginx.conf </strong>file. You can find the nginx.conf file in the below locations:</p><ul><li>Ubuntu : <em>/usr/local/openresty/nginx/nginx.conf</em></li><li>Windows: /openresty-VERSION/conf/nginx.conf</li><li>Mac: <em>/usr/local/Cellar/openresty/nginx/nginx.conf (using homebrew)</em></li></ul><p>For a basic Load Balancer with dynamic backends, there are two important operations that it should perform:</p><ol><li>API for adding hosts</li><li>Load Balancer</li><li>Reverse proxy server</li></ol><h4>Full Code of nginx.conf:</h4><pre>worker_processes  1;<br><br>#pid        logs/nginx.pid;<br><br>events {<br>    worker_connections  1024;<br>}<br><br>http {<br>    include       mime.types;<br>    default_type  application/octet-stream;<br>    sendfile        on;<br>    keepalive_timeout  65;<br>    <br>    -- Creating dict for hosts<br>    lua_shared_dict hosts 10m;<br><br>    upstream backend {<br>        server 0.0.0.1;<br>        balancer_by_lua_block {<br>           -- Import nginx balancer package<br>           local balancer = require &quot;ngx.balancer&quot;<br><br>           -- Getting hosts keys<br>           local hosts = ngx.shared.hosts<br>           local hosts_keys = hosts:get_keys()<br><br>           -- Getting total weight of all hosts<br>           local total_weight = 0<br><br>            for i, key in ipairs(hosts_keys) do<br>                total_weight = total_weight + hosts:get(key)<br>            end<br> <br>            -- Generating random number between 1 and total_weight<br>            local random_num = math.random(1, total_weight)<br>            total_weight = 0<br>            <br>            -- Apply weight random algorithm <br>            for i, key in ipairs(hosts_keys) do<br>                total_weight = total_weight + hosts:get(key)<br>                if random_num &lt; total_weight then<br>                    local host, port = string.match(key, &quot;^(.-):(.*)$&quot;)<br>                    ok, err = balancer.set_current_peer(host, port)<br>                    if not ok then<br>                     return ngx.exit(500)<br>                    end<br>                    break<br>                end<br>            end <br>        }<br>        keepalive_timeout  10ms;<br>    }<br><br>server {<br>        listen      8081;<br>        server_name localhost;<br><br>        location = /add-peer {<br>            content_by_lua_block {<br>              -- Getting post request body<br>              ngx.req.read_body()          <br>              <br>              -- Import library to work with json<br>              local cjson = require &quot;cjson&quot;<br><br>              -- Getting post request&#39;s args<br>              local post_args = ngx.req.get_post_args()<br>              local json_str = next(post_args)<br>              local json_obj = cjson.decode(json_str)<br>              local host = json_obj.host<br>              local weight = json_obj.weight<br>              <br>              -- Setting new host to hosts dict in (host, weight) format<br>              local hosts = ngx.shared.hosts<br>              hosts:set(host, weight)<br>              <br>              -- Return host and weight<br>              ngx.say(host)<br>              ngx.say(hosts:get(host))<br>           }<br>        }<br>    }<br><br>    server {<br>        listen       8080;<br>        server_name localhost;<br>        location / {<br>            proxy_pass http://backend;<br>        }<br>    }<br><br>}</pre><h3>API</h3><ol><li>The server directive sets up an NGINX server block listening on port 8081 with the server name &quot;localhost&quot;.</li><li>The location = /add-host directive specifies that this location block will be used only for requests with the exact path &quot;/add-host&quot;.</li><li>The content_by_lua_block directive allows you to execute custom Lua code to handle the request.</li><li>The Lua code begins by reading the request body using ngx.req.read_body(). This ensures that the request body is read and available for further processing.</li><li>The code then imports the “cjson” library, which provides functions to work with JSON data in Lua.</li><li>The ngx.req.get_post_args() function is used to retrieve the POST request arguments. It returns a table containing the key-value pairs of the arguments.</li><li>Since there is only one argument expected, next(post_args) retrieves the first (and only) key from the table.</li><li>The received JSON string is then decoded into a Lua table using cjson.decode(json_str). This converts the JSON data into a Lua object that can be easily accessed.</li><li>Next, it accesses the ngx.shared.hosts shared memory dictionary and sets the host as the key and weight as the corresponding value usin hosts:set(host, weight).</li><li>The code uses ngx.say() to return the host and its corresponding weight as the response body. These values are sent back to the client.</li></ol><p>In summary, this code sets up an NGINX server block that listens on port 8081. It handles a POST request to the “/add-host” endpoint, which expects a JSON payload containing the properties “host” and “weight”. It then stores the host and weight in the ngx.shared.hosts shared memory dictionary and returns the host and its weight as the response.</p><pre>server {<br>    listen      8081;<br>    server_name localhost;<br><br>    location = /add-host {<br>        content_by_lua_block {<br>          -- Getting post request body<br>          ngx.req.read_body()          <br>          <br>          -- Import library which provides functions to work with JSON<br>          local cjson = require &quot;cjson&quot;<br><br>          -- Retrieving the POST request arguments.<br>          local post_args = ngx.req.get_post_args()<br>          local json_str = next(post_args)<br>          local json_ obj = cjson.decode(json_str)<br>          local host = json_obj.host<br>          local weight = json_obj.weight<br>          <br>          -- Setting new host to hosts dict in (host, weight) format<br>          local hosts = ngx.shared.hosts<br>          hosts:set(host, weight)<br>          <br>          -- Return host and weight<br>          ngx.say(host)<br>          ngx.say(hosts:get(host))<br>       }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O3PmXV34fAvuYm4fVutORw.png" /></figure><h3>Load Balancer</h3><p>Load balancer in OpenResty with a dynamic set of backends requires using balancer_by_lua_block or balancer_by_lua_file.</p><ol><li>The upstream directive is used to define a group of servers that will be used as the backend for processing requests.</li><li>The server 0.0.0.1 line specifies a dummy server IP address. This server will not actually be used, but it is required for the configuration to be valid.</li><li>The balancer_by_lua_block directive allows you to execute custom Lua code to implement the load balancing logic.</li><li>The code starts by importing the NGINX balancer package with local balancer = require &quot;ngx.balancer&quot;. This package provides functions to interact with the load balancer module.</li><li>It retrieves the list of host keys from the ngx.shared.hosts shared memory dictionary using local hosts = ngx.shared.hosts and local hosts_keys = hosts:get_keys().</li><li>The variable total_weight is initialized as 0. It will be used to calculate the total weight of all hosts.</li><li>The code then iterates over each host key in the hosts_keys list. For each host, it retrieves its weight using hosts:get(key) and adds it to total_weight.</li><li>After calculating the total weight, the code generates a random number between 1 and total_weight using math.random(1, total_weight).</li><li>Another loop iterates over the host keys again, this time performing the weighted random algorithm. The algorithm checks if the randomly generated number is less than the cumulative weight. If it is, it selects that host as the current peer.</li><li>When a host is selected, the key is split into host and port using string.match(key, &quot;^(.-):(.*)$&quot;). The balancer.set_current_peer function is then called with host and port to set the current peer for load balancing.</li><li>Once a host is selected and set as the current peer, the loop breaks, and the load balancing process is complete.</li><li>The keepalive_timeout directive sets the maximum time in milliseconds that the connection to the backend server should be kept alive for subsequent requests.</li></ol><p>In summary, this code implements a weighted random load balancing algorithm using Lua scripting within NGINX. It selects a backend server from a pool of servers based on their weights defined in the ngx.shared.hosts shared memory dictionary.</p><pre>upstream backend {<br>    server 0.0.0.1;<br>    balancer_by_lua_block {<br>       -- Import nginx balancer package<br>       local balancer = require &quot;ngx.balancer&quot;<br><br>       -- Getting hosts keys<br>       local hosts = ngx.shared.hosts<br>       local hosts_keys = hosts:get_keys()<br><br>       -- Getting total weight of all hosts<br>       local total_weight = 0<br><br>        for i, key in ipairs(hosts_keys) do<br>            total_weight = total_weight + hosts:get(key)<br>        end<br><br>        -- Generating random number between 1 and total_weight<br>        local random_num = math.random(1, total_weight)<br>        total_weight = 0<br>        <br>        -- Apply weight random algorithm <br>        for i, key in ipairs(hosts_keys) do<br>            total_weight = total_weight + hosts:get(key)<br>            if random_num &lt; total_weight then<br>                local host, port = string.match(key, &quot;^(.-):(.*)$&quot;)<br>                ok, err = balancer.set_current_peer(host, port)<br>                if not ok then<br>                 return ngx.exit(500)<br>                end<br>                break<br>            end<br>        end <br>    }<br>    keepalive_timeout  10ms;<br>}</pre><h3>Reverse proxy server</h3><pre>server {<br>        listen       8080;<br>        server_name localhost;<br>        location / {<br>            proxy_pass http://backend;<br>        }<br>    }</pre><p>proxy_pass http://backend;: This line is the key part of this configuration. It instructs NGINX to act as a reverse proxy and forward all requests to the backend server specified by the URL &quot;<a href="http://backend/">http://backend</a>&quot;. NGINX will pass the requests it receives to the backend server, receive the response, and return it to the original client.</p><h3>Testing</h3><p>To test the load balancer, I launched 3 three servers. The first one runs on port 8091. The second one runs on port 8092 and the third one runs on port 8093. Then I added them to Load Balancer using /add-host . The weight of the first server is 2. The weight of the second server is 6 and the weight of the third server is 10. To test the Load Balancer we need to send request to localhost:8080/ . So, I sent 10 requests to see how the load balancer would distribute them across three servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y7xcyBia4iktWinidsKvGQ.png" /></figure><p>As a result, No request was sent to the server with weight 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aYbedMdEXdQmBRqHFnUu4g.png" /></figure><p>Two requests was sent to the server with weight 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MCyqYDNBKRkN5lisGHdAEg.png" /></figure><p>Eight requests was sent to the server with weight 10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-wgX3WCXfBI7jQSJmiqrg.png" /></figure><p>Congrats, your Load Balancer is ready! 🔥</p><h3>At Last:</h3><p>If you like this article, please follow or subscribe to receive high-quality content in time. Thank you for your support ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da5d3cc77b52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dockerize your Golang application]]></title>
            <link>https://medium.com/@nbenliogludev/how-to-dockerize-your-golang-application-e68a149e31c1?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/e68a149e31c1</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Fri, 05 May 2023 19:47:13 GMT</pubDate>
            <atom:updated>2023-05-05T19:47:13.247Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>The previous post (<a href="https://medium.com/@nikbenlioglu/how-to-build-a-to-do-list-telegram-bot-with-the-golang-postgresql-database-b77b1ec014ba">https://medium.com/@nikbenlioglu/how-to-build-a-to-do-list-telegram-bot-with-the-golang-postgresql-database-b77b1ec014ba</a>), I built a Telegram bot using Golang and Postgresql. So, in this post, I will show you how to Dockerize this project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-NUbnqNzOEEj3aR6.png" /></figure><p>To Dockerize the Golang project we first need to write Dockerfile.</p><pre>FROM golang:1.19.3-alpine3.16 as builder<br><br>WORKDIR /app<br>COPY /. ./<br><br>#apk add nano \ &amp;&amp; <br>RUN go mod download \<br>        &amp;&amp; go build -o /telegram-todolist .<br><br>FROM alpine:3.16.2<br>WORKDIR /app<br>COPY --from=builder telegram-todolist .<br>COPY .env .<br><br><br>CMD [&quot;./telegram-todolist&quot;]</pre><p>Then we need to build an image from this Dockerfile. To build an image run the “docker build .” command in the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTyQL3EHJ7qwLo-3RWzekA.png" /></figure><p>Let&#39;s list our Docker images. Run the “docker image ls” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*caLDDELVb-0r3IxYhxR87w.png" /></figure><p>To change the name of the image run “docker tag ‘IMAGE ID’ ‘new_name’ ” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*2bcoGwWqxW7tNcCI9hdTcw.png" /></figure><p>Your image is now displayed in Docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HhnqxFAVfRZvnnPrmrl9Ow.png" /></figure><p>Now let&#39;s push this image to dockerhub. To do this, we first need to log in dockerhub. Run “docker login” command to authorize.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WJ8noHPqZF_Z65pJGkMpPg.png" /></figure><p>Then we need to change the actual image&#39;s name to “dockerhub_nickname/image_name:tag”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*2npi8Ea2rk_WRQg2cgCLAg.png" /></figure><p>Now we can push our image by running “docker push ‘image_name’” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*_w1wV1g4vaqjQl3ODP4d8Q.png" /></figure><p>Now you can find your image on dockerhub.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xe-Q3xA-NMESBESTKFtiIQ.png" /></figure><p>Now to combine the project image and database image into one container we need to create docker-compose file. There are two services in the file below. The first one is the Golang project’s image. The second one is PostgreSQL’s image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*YSJyEr1n6BmFxORgnzSUSw.png" /></figure><p>After creating the docker-compose file run it by running “file_name up” command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6oOp1lCjQCXqERxugBobDA.png" /></figure><p>As a result, you will find a ready container in docker.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LWRWodJfiVGjmOZrCsVj4w.png" /></figure><p>Congrats, your container is running! 🔥</p><h3>At Last:</h3><p>If you like this article, please follow or subscribe to receive high-quality content in time. Thank you for your support ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e68a149e31c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Telegram Bot with the GOLANG (PostgreSQL)]]></title>
            <link>https://medium.com/@nbenliogludev/how-to-build-a-to-do-list-telegram-bot-with-the-golang-postgresql-database-b77b1ec014ba?source=rss-796737a1c483------2</link>
            <guid isPermaLink="false">https://medium.com/p/b77b1ec014ba</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nikolay Benlioglu]]></dc:creator>
            <pubDate>Mon, 01 May 2023 15:36:46 GMT</pubDate>
            <atom:updated>2023-05-03T17:32:17.331Z</atom:updated>
            <content:encoded><![CDATA[<p>Github: <a href="https://github.com/nikben08/todolist-telegram_bot-medium">https://github.com/nikben08/todolist-telegram_bot-medium</a></p><h3>Register your bot on Telegram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*AiYemKIiRyo3doCWtW_uOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*2J5U0lOqf-c-vW08B2d1tA.png" /></figure><h3>Let’s create a project</h3><p>There are 3 layers in my project.</p><ol><li>The handlers layer is the layer that processes incoming commands.</li><li>The services layer is the layer that implements business logic.</li><li>The repositories layer is the layer that we use to perform operations with the database.</li></ol><p>The picture below shows the structure of the project</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*njujmtxGYVIw39nf2F3GFQ.png" /></figure><ol><li>Create .env file.</li></ol><p>First of all, we need to create .env file where we will store the environment variables like the Telegram API token, Project’s port, DBHost, etc.</p><pre>TELEGRAM_APITOKEN= #your telegram api toke<br>PORT=83<br>POSTGRES_HOST=127.0.0.1<br>POSTGRES_USER=postgres<br>POSTGRES_PASSWORD=0811<br>POSTGRES_DATABASE_NAME=todolist<br>POSTGRES_PORT=5432<br>SSL_MODE=&quot;disable&quot;</pre><p>2. Create config file (config &gt; config.go).</p><p>Then we need to create config.go file. In that file we need to write a function that gets the environment variable from .env file.</p><pre>package config<br><br>import (<br> &quot;fmt&quot;<br> &quot;os&quot;<br><br> &quot;github.com/joho/godotenv&quot;<br>)<br><br>// Config func to get env value from key ---<br>func Config(key string) string {<br> // load .env file<br> err := godotenv.Load(&quot;.env&quot;)<br> if err != nil {<br>  fmt.Print(&quot;Error loading .env file&quot;)<br> }<br> return os.Getenv(key)<br>}</pre><p>3. Create a telegram client file (clients &gt; telegram.go).</p><p>Then we need to create a Telegram client file. In that file, I wrote a function that creates a connection with the Telegram bot and returns the connection as a pointer. As a telegram library, I use go-telegram-bot-api.</p><pre>package clients<br><br>import (<br> &quot;log&quot;<br> &quot;telegram-todolist/config&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Init() *tgbotapi.BotAPI {<br> bot, err := tgbotapi.NewBotAPI(config.Config(&quot;TELEGRAM_APITOKEN&quot;))<br> if err != nil {<br>  log.Panic(err)<br> }<br> bot.Debug = true<br> return bot<br>}</pre><p>4. Create a database connection file (database &gt; database.go)</p><p>Next, we need to create database.go file. In that file, I wrote a function that creates a connection with PostgreSQL. Then that function recreates the database by dropping todolist database if it exists and creating the new one. Then the function creates a connection to the database it previously created. Then the Init function makes migration and returns the database connection as a pointer.</p><pre>package database<br><br>import (<br> &quot;fmt&quot;<br> &quot;log&quot;<br> &quot;telegram-todolist/config&quot;<br> &quot;telegram-todolist/models&quot;<br><br> _ &quot;github.com/lib/pq&quot;<br> &quot;gorm.io/driver/postgres&quot;<br> &quot;gorm.io/gorm&quot;<br>)<br><br>func Init() *gorm.DB {<br> //Connect to database<br> dsn := fmt.Sprintf(&quot;host=%s user=%s password=%s port=%s, dbname=%s&quot;, config.Config(&quot;POSTGRES_HOST&quot;), config.Config(&quot;POSTGRES_USER&quot;), config.Config(&quot;POSTGRES_PASSWORD&quot;), config.Config(&quot;POSTGRES_PORT&quot;), &quot;postgres&quot;)<br> DB, err := gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> if err := DB.Exec(&quot;DROP DATABASE IF EXISTS todolist;&quot;).Error; err != nil {<br>  panic(err)<br> }<br><br> if err := DB.Exec(&quot;CREATE DATABASE todolist&quot;).Error; err != nil {<br>  panic(err)<br> }<br><br> dsn = fmt.Sprintf(&quot;host=%s user=%s password=%s dbname=%s port=%s&quot;, config.Config(&quot;POSTGRES_HOST&quot;), config.Config(&quot;POSTGRES_USER&quot;), config.Config(&quot;POSTGRES_PASSWORD&quot;), config.Config(&quot;POSTGRES_DATABASE_NAME&quot;), config.Config(&quot;POSTGRES_PORT&quot;))<br> DB, err = gorm.Open(postgres.Open(dsn), &amp;gorm.Config{})<br> if err != nil {<br>  log.Fatal(err)<br> }<br><br> // Migrate tables<br> DB.AutoMigrate(&amp;models.Task{})<br><br> return DB<br>}</pre><p>5. Create model Task (models &gt; task.go)</p><p>Next, we need to create a model that we will use to create todos. I created the model by creating a Task struct. Task struct has an ID that automatically generates. As an ID I use uuid from Google. The task also has ChatId that we will use as a user identifier and Task containing text with the todo.</p><pre>package models<br><br>import (<br> &quot;github.com/google/uuid&quot;<br>)<br><br>type Task struct {<br> ID     uuid.UUID `gorm:&quot;type:uuid;default:gen_random_uuid();&quot;`<br> ChatId int64     `gorm:&quot;chat_id&quot;`<br> Task   string    `gorm:&quot;task&quot;`<br>}</pre><p>6. Create handler functions (handlers &gt; init.go, commands.go, callbacks.go, messages.go)</p><p>init.go</p><p>The Init function checks updates and determines the type of update.</p><pre>package handlers<br><br>import (<br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Init(bot *tgbotapi.BotAPI) {<br> u := tgbotapi.NewUpdate(0)<br> u.Timeout = 60<br> updates := bot.GetUpdatesChan(u)<br> // Loop through each update.<br> for update := range updates {<br>  if update.CallbackQuery != nil {<br>   Callbacks(bot, update)<br>  } else if update.Message.IsCommand() {<br>   Commands(bot, update)<br>  } else {<br>   Messages(bot, update)<br>  }<br> }<br>}</pre><p>commands.go</p><p>The Commands function handles commands that come from Init function.</p><pre>package handlers<br><br>import (<br> &quot;telegram-todolist/services&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Commands(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> switch update.Message.Command() {<br> case &quot;start&quot;:<br>  services.Start(bot, update)<br> case &quot;set_todo&quot;:<br>  services.SetTask(bot, update)<br> case &quot;delete_todo&quot;:<br>  services.DeleteTask(bot, update)<br> case &quot;show_all_todos&quot;:<br>  services.ShowAllTasks(bot, update)<br> }<br>}</pre><p>callbacks.go</p><p>The Сallbacks function handles callbacks. At the beginning of the function, we split update.CallbackQuery.Data to get command and taskId (todo ID).</p><pre>package handlers<br><br>import (<br> &quot;telegram-todolist/services&quot;<br> &quot;telegram-todolist/utils&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Callbacks(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> cmd, taskId := utils.GetKeyValue(update.CallbackQuery.Data)<br> switch {<br> case cmd == &quot;delete_task&quot;:<br>  services.DeleteTaskCallback(bot, update, taskId)<br> }<br>}</pre><p>messages.go</p><p>The messages function handles received messages. As a message we send only Todo’s text, that&#39;s why we don&#39;t need to use a case switch here.</p><pre>package handlers<br><br>import (<br> &quot;telegram-todolist/services&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Messages(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> services.SetTaskCallback(bot, update)<br>}</pre><p>7. Create the services layer (services &gt; tasks.go)</p><p>In the services layer, I implement the business logic of the project. DeleteTask function creates a markup keyboard of todos so that the user can select the todo to be deleted.</p><pre>package services<br><br>import (<br> &quot;fmt&quot;<br><br> &quot;telegram-todolist/keyboards&quot;<br> &quot;telegram-todolist/repositories&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func Start(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> text := &quot;Hi, here you can create todos for your todolist.&quot;<br> msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)<br> msg.ReplyMarkup = keyboards.CmdKeyboard()<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}<br><br>func SetTask(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> text := &quot;Please, write todo.&quot;<br> msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}<br><br>func SetTaskCallback(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> text := &quot;Todo successfully created&quot;<br><br> err := repositories.SetTask(update)<br> if err != nil {<br>  text = &quot;Couldnt set task&quot;<br> }<br><br> msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}<br><br>func DeleteTask(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> data, _ := repositories.GetAllTasks(update.Message.Chat.ID)<br> var btns []tgbotapi.InlineKeyboardButton<br> for i := 0; i &lt; len(data); i++ {<br>  btn := tgbotapi.NewInlineKeyboardButtonData(data[i].Task, &quot;delete_task=&quot;+data[i].ID.String())<br>  btns = append(btns, btn)<br> }<br><br> var rows [][]tgbotapi.InlineKeyboardButton<br> for i := 0; i &lt; len(btns); i += 2 {<br>  if i &lt; len(btns) &amp;&amp; i+1 &lt; len(btns) {<br>   row := tgbotapi.NewInlineKeyboardRow(btns[i], btns[i+1])<br>   rows = append(rows, row)<br>  } else if i &lt; len(btns) {<br>   row := tgbotapi.NewInlineKeyboardRow(btns[i])<br>   rows = append(rows, row)<br>  }<br> }<br> fmt.Println(len(rows))<br> var keyboard = tgbotapi.InlineKeyboardMarkup{InlineKeyboard: rows}<br> //keyboard.InlineKeyboard = rows<br><br> text := &quot;Please, select todo you want to delete&quot;<br> msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)<br> msg.ReplyMarkup = keyboard<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}<br><br>func DeleteTaskCallback(bot *tgbotapi.BotAPI, update tgbotapi.Update, taskId string) {<br> text := &quot;Task successfully deleted&quot;<br><br> err := repositories.DeleteTask(taskId)<br> if err != nil {<br>  text = &quot;Couldnt delete task&quot;<br> }<br><br> msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, text)<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}<br><br>func ShowAllTasks(bot *tgbotapi.BotAPI, update tgbotapi.Update) {<br> text := &quot;Tasks: \n&quot;<br><br> tasks, err := repositories.GetAllTasks(update.Message.Chat.ID)<br> if err != nil {<br>  text = &quot;Couldnt get tasks&quot;<br> }<br><br> for i := 0; i &lt; len(tasks); i++ {<br>  text += tasks[i].Task + &quot; \n&quot;<br> }<br><br> msg := tgbotapi.NewMessage(update.Message.Chat.ID, text)<br> if _, err := bot.Send(msg); err != nil {<br>  panic(err)<br> }<br>}</pre><p>8. Create repositories layer (repositories &gt; repository.go, tasks.go)</p><p>repository.go</p><p>In the repository file, we create a connection to the database.</p><pre>package repositories<br><br>import (<br> &quot;telegram-todolist/database&quot;<br><br> &quot;gorm.io/gorm&quot;<br>)<br><br>var DB *gorm.DB = database.Init()</pre><p>tasks.go</p><p>In task.go file we create functions that we use in the services layer. These functions we use to perform operations with the database.</p><pre>package repositories<br><br>import (<br> &quot;telegram-todolist/models&quot;<br><br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func SetTask(update tgbotapi.Update) error {<br> task := models.Task{<br>  ChatId: update.Message.Chat.ID,<br>  Task:   update.Message.Text,<br> }<br><br> if result := DB.Create(&amp;task); result.Error != nil {<br>  return result.Error<br> }<br> return nil<br>}<br><br>func DeleteTask(taskId string) error {<br> if result := DB.Where(&quot;id = ?&quot;, taskId).Delete(&amp;models.Task{}); result.Error != nil {<br>  return result.Error<br> }<br> return nil<br>}<br><br>func GetAllTasks(chatId int64) ([]models.Task, error) {<br> var tasks []models.Task<br> if result := DB.Where(&quot;chat_id = ?&quot;, chatId).Find(&amp;tasks); result.Error != nil {<br>  return tasks, result.Error<br> }<br> return tasks, nil<br>}</pre><p>9. Create commands keyboard file (keyboards &gt; cmd_keyboard.go)</p><p>CmdKeyaboard creates a keyboard of commands.</p><pre>package keyboards<br><br>import (<br> tgbotapi &quot;github.com/go-telegram-bot-api/telegram-bot-api/v5&quot;<br>)<br><br>func CmdKeyboard() tgbotapi.ReplyKeyboardMarkup {<br> var cmdKeyboard = tgbotapi.NewReplyKeyboard(<br>  tgbotapi.NewKeyboardButtonRow(<br>   tgbotapi.NewKeyboardButton(&quot;/set_todo&quot;),<br>  ),<br>  tgbotapi.NewKeyboardButtonRow(<br>   tgbotapi.NewKeyboardButton(&quot;/delete_todo&quot;),<br>  ),<br>  tgbotapi.NewKeyboardButtonRow(<br>   tgbotapi.NewKeyboardButton(&quot;/show_all_todos&quot;),<br>  ),<br> )<br> return cmdKeyboard<br>}</pre><p>10. Create main.go file</p><p>Main function sets the app variable, telegram client, and calls handlers.Init() function.</p><pre>package main<br><br>import (<br> &quot;log&quot;<br> &quot;telegram-todolist/clients&quot;<br> &quot;telegram-todolist/config&quot;<br> &quot;telegram-todolist/handlers&quot;<br><br> &quot;github.com/gofiber/fiber/v2&quot;<br> &quot;github.com/gofiber/fiber/v2/middleware/cors&quot;<br>)<br><br>func main() {<br> app := fiber.New()<br> app.Use(cors.New(cors.Config{<br>  AllowOrigins: &quot;*&quot;,<br>  AllowHeaders: &quot;*&quot;,<br> }))<br> bot := clients.Init()<br> handlers.Init(bot)<br> log.Fatal(app.Listen(&quot;:&quot; + config.Config(&quot;PORT&quot;)))<br>}</pre><p>11. Run “go mod init project_name” and “go mod tidy” commands in terminal. Then run “go run main.go” command.</p><p>Congrats, your bot is now live! 🔥</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvlJeAHSHD5EDFL_MIAi7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rC52Gy97SlhSoWWBKHdq0g.png" /></figure><h3>At Last:</h3><p>If you like this article, please follow or subscribe to receive high-quality content in time. Thank you for your support ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b77b1ec014ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>