<?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 Emre Gök on Medium]]></title>
        <description><![CDATA[Stories by Emre Gök on Medium]]></description>
        <link>https://medium.com/@emre.gok?source=rss-e83923056ba7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xe0kgkbr0X7zOOnamDjrJQ.jpeg</url>
            <title>Stories by Emre Gök on Medium</title>
            <link>https://medium.com/@emre.gok?source=rss-e83923056ba7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:52:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emre.gok/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[Deep Copy confusion in Golang]]></title>
            <link>https://medium.com/@emre.gok/deep-copy-confusion-in-golang-9aeb9ef6498f?source=rss-e83923056ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aeb9ef6498f</guid>
            <category><![CDATA[struct]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[shallow-copy]]></category>
            <category><![CDATA[pointers]]></category>
            <category><![CDATA[deep-copy]]></category>
            <dc:creator><![CDATA[Emre Gök]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 12:22:03 GMT</pubDate>
            <atom:updated>2024-06-30T12:22:03.513Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will address two important concepts when copying variables in the Go language: deep copy and shallow copy. While working with primitive types in our code, we generally handle their values, but in structures like structs that hold multiple data types, we may work with pointers for performance purposes. This is precisely where the issues of data duplication that are prone to errors arise, which we will discuss.</p><p>I.I. <em>Lets begin with example:</em></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>type Product struct {<br> Name      string<br> Model     string<br> PriceInfo *PriceInfo<br>}<br><br>type PriceInfo struct {<br> Price    float32<br> TaxPrice float32<br> TaxRate  float32 //percentage<br>}<br><br>func main() {<br> product := Product{<br>  Name:  &quot;Example Product Name&quot;,<br>  Model: &quot;Shoes&quot;,<br>  PriceInfo: &amp;PriceInfo{<br>   Price:    119.99,<br>   TaxPrice: 11.99,<br>   TaxRate:  10,<br>  },<br> }<br><br> // Copy process<br> copyProduct := product<br><br> fmt.Println(&quot;#Product Infos:&quot;)<br> fmt.Printf(&quot;product.Name: %s, product.Model: %s\n&quot;, product.Name, product.Model)<br> fmt.Printf(&quot;product.PriceInfo.Price: %.2f, product.PriceInfo.TaxPrice: %.2f, product.PriceInfo.TaxRate: %.2f\n&quot;, product.PriceInfo.Price, product.PriceInfo.TaxPrice, product.PriceInfo.TaxRate)<br> fmt.Println(&quot;---&quot;)<br> fmt.Println(&quot;#CopyProduct Infos:&quot;)<br> fmt.Printf(&quot;copyProduct.Name: %s, copyProduct.Model: %s\n&quot;, copyProduct.Name, copyProduct.Model)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price: %.2f, copyProduct.PriceInfo.TaxPrice: %.2f, copyProduct.PriceInfo.TaxRate: %.2f\n&quot;, copyProduct.PriceInfo.Price, copyProduct.PriceInfo.TaxPrice, copyProduct.PriceInfo.TaxRate)<br>}</pre><figure><img alt="E.g., Product is copied as shallowed." src="https://cdn-images-1.medium.com/max/1024/1*3nliahOCGV1tUmsKGYen-Q.png" /><figcaption>As you can see, copied of product is same as original product variable. Everything is fine right now.</figcaption></figure><p>I.II.<em> Let’s update the name and price of the product value we copied and then examine what happens.</em></p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>type Product struct {<br> Name      string<br> Model     string<br> PriceInfo *PriceInfo<br>}<br><br>type PriceInfo struct {<br> Price    float32<br> TaxPrice float32<br> TaxRate  float32 //percentage<br>}<br><br>func main() {<br> product := Product{<br>  Name:  &quot;Example Product Name&quot;,<br>  Model: &quot;Shoes&quot;,<br>  PriceInfo: &amp;PriceInfo{<br>   Price:    119.99,<br>   TaxPrice: 11.99,<br>   TaxRate:  10,<br>  },<br> }<br><br> // Copy process<br> copyProduct := product<br><br> fmt.Println(&quot;#Product Infos:&quot;)<br> fmt.Printf(&quot;product.Name: %s, product.Model: %s\n&quot;, product.Name, product.Model)<br> fmt.Printf(&quot;product.PriceInfo.Price: %.2f, product.PriceInfo.TaxPrice: %.2f, product.PriceInfo.TaxRate: %.2f\n&quot;, product.PriceInfo.Price, product.PriceInfo.TaxPrice, product.PriceInfo.TaxRate)<br> fmt.Println(&quot;---&quot;)<br> fmt.Println(&quot;#CopyProduct Infos:&quot;)<br> fmt.Printf(&quot;copyProduct.Name: %s, copyProduct.Model: %s\n&quot;, copyProduct.Name, copyProduct.Model)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price: %.2f, copyProduct.PriceInfo.TaxPrice: %.2f, copyProduct.PriceInfo.TaxRate: %.2f\n&quot;, copyProduct.PriceInfo.Price, copyProduct.PriceInfo.TaxPrice, copyProduct.PriceInfo.TaxRate)<br><br> // Change name and price of copyProduct<br> copyProduct.Name = &quot;Example Copy Product Name&quot;<br> copyProduct.PriceInfo.Price = 139.99<br><br> // Let&#39;s see differences<br> fmt.Println()<br> fmt.Println(&quot;### Differences after value changing ###&quot;)<br> fmt.Println()<br><br> // Final situation<br> fmt.Println(&quot;#Product Infos After Value Changing:&quot;)<br> fmt.Printf(&quot;product.Name: %s, product.Model: %s\n&quot;, product.Name, product.Model)<br> fmt.Printf(&quot;product.PriceInfo.Price: %.2f, product.PriceInfo.TaxPrice: %.2f, product.PriceInfo.TaxRate: %.2f\n&quot;, product.PriceInfo.Price, product.PriceInfo.TaxPrice, product.PriceInfo.TaxRate)<br> fmt.Println(&quot;---&quot;)<br> fmt.Println(&quot;#CopyProduct Infos After Value Changing:&quot;)<br> fmt.Printf(&quot;copyProduct.Name: %s, copyProduct.Model: %s\n&quot;, copyProduct.Name, copyProduct.Model)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price: %.2f, copyProduct.PriceInfo.TaxPrice: %.2f, copyProduct.PriceInfo.TaxRate: %.2f\n&quot;, copyProduct.PriceInfo.Price, copyProduct.PriceInfo.TaxPrice, copyProduct.PriceInfo.TaxRate)<br>}</pre><figure><img alt="E.g., After sallowed copy result and differences on variables." src="https://cdn-images-1.medium.com/max/1024/1*yzfizhiyI3WHawCGjQRUbA.png" /><figcaption>The result of value changes made on the copied product variable.</figcaption></figure><blockquote>As seen in the example code output above, changing the Name field on copyProduct only affects itself, while changing the Price value also affects the product variable, making both values 139.99. The issue here stems from performing a `<strong>shallow copy`</strong>. Since we directly assigned one variable to another, the value types were correctly copied as values. However, because the PriceInfo struct value is a reference, we copied its address value. To look deeper into this, I will share the output of the address values below.</blockquote><pre> // Reference comparison<br> fmt.Println()<br> fmt.Println(&quot;### Pointers of changed vals ###&quot;)<br> fmt.Printf(&quot;product.Name pointer: %p\n&quot;, &amp;product.Name)<br> fmt.Printf(&quot;copyProduct.Name pointer: %p\n&quot;, &amp;copyProduct.Name)<br> fmt.Println(&quot;---&quot;)<br> fmt.Printf(&quot;product.PriceInfo.Price pointer: %p\n&quot;, &amp;product.PriceInfo.Price)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price pointer: %p\n&quot;, &amp;copyProduct.PriceInfo.Price)</pre><p>Let’s put the pointer output code above at the bottom of the code under heading I.II and run our code again and see the difference.</p><figure><img alt="E.g., Pointer comparison after shallow copy." src="https://cdn-images-1.medium.com/max/838/1*tkGdUNRoGInTAF4eQ_q60A.png" /><figcaption>Pointers comparison</figcaption></figure><blockquote>As seen in the comparison of the pointers in the output image above, despite being able to write the Name field to different addresses as a result of the copy, we copied the references of the values inside PriceInfo. As shown in the image, the references pointed to by the Price values in “product” and “copyProduct” are the same. Therefore, changes affect both sides. This can lead to data and synchronization issues within the code. One way to solve this is by performing a `<strong>deep copy`</strong>.</blockquote><p>II.I. Let’s take it with deep copy:</p><pre>package main<br><br>import (<br> &quot;fmt&quot;<br>)<br><br>type Product struct {<br> Name      string<br> Model     string<br> PriceInfo *PriceInfo<br>}<br><br>type PriceInfo struct {<br> Price    float32<br> TaxPrice float32<br> TaxRate  float32 //percentage<br>}<br><br>func main() {<br> product := Product{<br>  Name:  &quot;Example Product Name&quot;,<br>  Model: &quot;Shoes&quot;,<br>  PriceInfo: &amp;PriceInfo{<br>   Price:    119.99,<br>   TaxPrice: 11.99,<br>   TaxRate:  10,<br>  },<br> }<br><br> // Create copyProduct with new PriceInfo<br> copyProduct := Product{<br>  PriceInfo: &amp;PriceInfo{},<br> }<br><br> // Deep copy<br> copyProduct.Name = product.Name<br> copyProduct.Model = product.Name<br> copyProduct.PriceInfo.Price = product.PriceInfo.Price<br> copyProduct.PriceInfo.TaxPrice = product.PriceInfo.TaxPrice<br> copyProduct.PriceInfo.TaxRate = product.PriceInfo.TaxRate<br><br> fmt.Println(&quot;#Product Infos:&quot;)<br> fmt.Printf(&quot;product.Name: %s, product.Model: %s\n&quot;, product.Name, product.Model)<br> fmt.Printf(&quot;product.PriceInfo.Price: %.2f, product.PriceInfo.TaxPrice: %.2f, product.PriceInfo.TaxRate: %.2f\n&quot;, product.PriceInfo.Price, product.PriceInfo.TaxPrice, product.PriceInfo.TaxRate)<br> fmt.Println(&quot;---&quot;)<br> fmt.Println(&quot;#CopyProduct Infos:&quot;)<br> fmt.Printf(&quot;copyProduct.Name: %s, copyProduct.Model: %s\n&quot;, copyProduct.Name, copyProduct.Model)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price: %.2f, copyProduct.PriceInfo.TaxPrice: %.2f, copyProduct.PriceInfo.TaxRate: %.2f\n&quot;, copyProduct.PriceInfo.Price, copyProduct.PriceInfo.TaxPrice, copyProduct.PriceInfo.TaxRate)<br><br> // Change name and price of copyProduct<br> copyProduct.Name = &quot;Example Copy Product Name&quot;<br> copyProduct.PriceInfo.Price = 139.99<br><br> // Let&#39;s see differences<br> fmt.Println()<br> fmt.Println(&quot;### Differences after value changing ###&quot;)<br> fmt.Println()<br><br> // Final situation<br> fmt.Println(&quot;#Product Infos After Value Changing:&quot;)<br> fmt.Printf(&quot;product.Name: %s, product.Model: %s\n&quot;, product.Name, product.Model)<br> fmt.Printf(&quot;product.PriceInfo.Price: %.2f, product.PriceInfo.TaxPrice: %.2f, product.PriceInfo.TaxRate: %.2f\n&quot;, product.PriceInfo.Price, product.PriceInfo.TaxPrice, product.PriceInfo.TaxRate)<br> fmt.Println(&quot;---&quot;)<br> fmt.Println(&quot;#CopyProduct Infos After Value Changing:&quot;)<br> fmt.Printf(&quot;copyProduct.Name: %s, copyProduct.Model: %s\n&quot;, copyProduct.Name, copyProduct.Model)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price: %.2f, copyProduct.PriceInfo.TaxPrice: %.2f, copyProduct.PriceInfo.TaxRate: %.2f\n&quot;, copyProduct.PriceInfo.Price, copyProduct.PriceInfo.TaxPrice, copyProduct.PriceInfo.TaxRate)<br><br> // Reference comparison<br> fmt.Println()<br> fmt.Println(&quot;### Pointers of changed vals ###&quot;)<br> fmt.Printf(&quot;product.Name pointer: %p\n&quot;, &amp;product.Name)<br> fmt.Printf(&quot;copyProduct.Name pointer: %p\n&quot;, &amp;copyProduct.Name)<br> fmt.Println(&quot;---&quot;)<br> fmt.Printf(&quot;product.PriceInfo.Price pointer: %p\n&quot;, &amp;product.PriceInfo.Price)<br> fmt.Printf(&quot;copyProduct.PriceInfo.Price pointer: %p\n&quot;, &amp;copyProduct.PriceInfo.Price)<br>}</pre><figure><img alt="E.g., Deep copy." src="https://cdn-images-1.medium.com/max/1024/1*6g5SCPZdds_CBtRj19PG0A.png" /></figure><blockquote>By using the deep copy method, we created a new Product struct and a new PriceInfo struct within it, resulting in a clean variable. Then, we copied the values one by one. As seen in the output, changing the Price on copyProduct does not affect the Price value in the product variable. If we look at the output again, we will see that the reference values are also different. This ensured a safe data copying process.</blockquote><p>III. Conclusion</p><p>In light of these experiments, shallow copying can cause issues with struct types. When copying reference values, deep copy problems can arise because what you are actually copying is the pointer. This can lead to data confusion in commonly used areas and cause your program to produce undesired results.</p><p><em>Therefore, in such operations, it is always preferable to create a clean data structure and perform the copying on it.</em> This approach is simple, effective, and secure. Of course, packages related to these needs can also be used. Be cautious when working with references. When using objects instantiated by packages included in our project and passing them as parameters to functions, check whether you might encounter such issues. I hope this has been helpful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aeb9ef6498f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuration Pattern in `Go`]]></title>
            <link>https://medium.com/@emre.gok/configuration-patter-in-go-d59db2deaa4d?source=rss-e83923056ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d59db2deaa4d</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[configuration]]></category>
            <category><![CDATA[options]]></category>
            <category><![CDATA[functional]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Emre Gök]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 19:06:34 GMT</pubDate>
            <atom:updated>2024-03-31T19:19:27.568Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to dynamically manage the parameters we give and use during the installation phase of the objects of the structures we create. For example, let’s assume that there is a basic server and we will start it with the values ​​given according to its parameters.</p><pre>package server<br><br>// Server struct<br>type Server struct {<br>    WriteTimeout  time.Duration<br>    ReadTimeout   time.Duration<br>    Port          string<br>    TLS           bool<br>}<br><br>type ServerOption func(*Server)<br><br>// Server constructor<br>func NewServer(options ...Option) *Server {<br>    // Create instance<br>    srv := &amp;Server{}<br><br>    // Set options<br>    for _, option := range options {<br>        option(srv)<br>    }<br><br>    return srv<br>}<br><br>// WithWriteTimeout<br>func WithWriteTimeout(writeTimeout time.Duration) ServerOption {<br>    return func(s *Server) {<br>        s.WriteTimeout = writeTimeout<br>    }<br>}<br><br>// WithReadTimeout<br>func WithReadTimeout(readTimeout int) ServerOption {<br>    return func(s *Server) {<br>        s.readTimeout = readTimeout<br>    }<br>}<br><br>// WithPort<br>func WithPort(port string) ServerOption {<br>    return func(s *Server) {<br>        s.Port = port<br>    }<br>}<br><br>// WithTLS<br>func WithTLS(tls bool) ServerOption {<br>    return func(s *Server) {<br>        s.TLS = tpl<br>    }<br>}</pre><blockquote>Usage:</blockquote><pre>package app<br><br>import &quot;myapp/server&quot;<br><br>func InitApp() {<br>    server := server.NewServer(<br>      server.WithWriteTimeout(time.Second * 60),<br>      server.WithReadTimeout(time.Second * 60),<br>      server.WithPort(&quot;8081&quot;),<br>      server.WithTLS(true),<br>    )<br><br>    // The rest of the codes can be continued...<br>}</pre><p><em>We can also add another feature to this usage. We can collect the optional methods you use for configuration settings under struct instead of making them global for the package.</em></p><pre>package server<br><br>// Server struct<br>type Server struct {<br>    WriteTimeout  time.Duration<br>    ReadTimeout   time.Duration<br>    Port          string<br>    TLS           bool<br>}<br><br>type serverOption func(*Server)<br><br>// Server option functions struct<br>type ServerOpsFuncs struct{}<br><br>// ServerOpsFuncs constructor<br>func NewServerOpsFuncs() *serverOpsFuncs {<br> return &amp;serverOpsFuncs{}<br>}<br><br>// Server constructor<br>func NewServer(options ...Option) *Server {<br>    // Create instance<br>    srv := &amp;Server{}<br><br>    // Set options<br>    for _, option := range options {<br>        option(srv)<br>    }<br><br>    return srv<br>}<br><br>// WithWriteTimeout<br>func (*ServerOpsFuncs) WithWriteTimeout(writeTimeout time.Duration) serverOption {<br>    return func(s *Server) {<br>        s.WriteTimeout = writeTimeout<br>    }<br>}<br><br>// WithReadTimeout<br>func (*ServerOpsFuncs) WithReadTimeout(readTimeout int) serverOption {<br>    return func(s *Server) {<br>        s.readTimeout = readTimeout<br>    }<br>}<br><br>// WithPort<br>func (*ServerOpsFuncs) WithPort(port string) serverOption {<br>    return func(s *Server) {<br>        s.Port = port<br>    }<br>}<br><br>// WithTLS<br>func (*ServerOpsFuncs) WithTLS(tls bool) serverOption {<br>    return func(s *Server) {<br>        s.TLS = tpl<br>    }<br>}</pre><blockquote>Usage:</blockquote><pre>package app<br><br>import &quot;myapp/server&quot;<br><br>func InitApp() {<br>    srvOpsFuncs := server.NewServerOpsFuncs()<br><br>    server := server.NewServer(<br>      srvOpsFuncs.WithWriteTimeout(time.Second * 60),<br>      srvOpsFuncs.WithReadTimeout(time.Second * 60),<br>      srvOpsFuncs.WithPort(&quot;8081&quot;),<br>      srvOpsFuncs.WithTLS(true),<br>    )<br><br>    // The rest of the codes can be continued...<br>}</pre><p>As a result, we can use this setup for our structures with many constituent parameters that we change with dynamic settings. It will add flexibility and uniqueness to us. Maybe we can put some effort into the initial setup, it will be an ideal and comprehensive approach for wide usage.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d59db2deaa4d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Manage Docker Commands with `Make`]]></title>
            <link>https://medium.com/@emre.gok/manage-docker-commands-with-make-76b8292b4479?source=rss-e83923056ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b8292b4479</guid>
            <category><![CDATA[shell]]></category>
            <category><![CDATA[make]]></category>
            <category><![CDATA[makefile]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Emre Gök]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 11:00:54 GMT</pubDate>
            <atom:updated>2023-06-15T11:00:54.214Z</atom:updated>
            <content:encoded><![CDATA[<p>While compiling or running our programs, the commands are long and complex, even we can’t remember and look at the documents. In this article, we will try to manage our images in a simple and only way using makefile over docker commands. On the other hand, you can use the makefile not just here or in a specific language, you can use it regardless of the environment. Let’s start with what is what.</p><p><strong>What are Make and Makefile<br><em>* Make: </em></strong>The Make application is designed to automate the recompilation process of programs, saving time by recompiling only the parts that have changed, and always do the operations automatically in the correct order. Of course, there are dependencies that enable these operations to be performed. It uses a file called “makefile or Makefile” to graph this dependency and creates scripts that are used to be passed to the shell.<br><strong><em>* MakeFile: </em></strong>It consists of lines of text describing a file or rule name. With the parameters you set in these files, the processes such as compiling your project, building up, removing it from the environment or deleting the compiled files can be easily handled with a command.</p><figure><img alt="makefile + docker" src="https://cdn-images-1.medium.com/max/1024/1*KZ6Z1720MjCn0eOv5fqS-A.jpeg" /></figure><p><strong>Creating sample docker tools</strong><br>In this example, I would like to work on an environment where the docker tools and makefile are in different directories.</p><figure><img alt="docker and makefile sample folder structure" src="https://cdn-images-1.medium.com/max/512/1*htX11OXU_qCHa839qLt_Jw.png" /><figcaption>View I. Docker tools and makefile sample folder structure</figcaption></figure><p>You can also use simple Dockerfile and compose contents for example.</p><blockquote>Sample of Dockerfile:</blockquote><pre>FROM alpine as base<br><br>CMD [&quot;echo&quot;, &quot;Hello World!&quot;]</pre><blockquote>Sample of docker-compose.yml:</blockquote><pre>version: &quot;3.9&quot;<br><br>services:<br>  app:<br>    container_name: docker-makefile<br>    build:<br>      dockerfile: Dockerfile<br>      context: .<br>      target: base<br>    volumes:<br>      - ../:/app/base</pre><p><strong>Manage docker image operations with Makefile<br></strong>When defining a command in the file, the command name is written and a colon is placed. One bottom line is passed and instructions are written.</p><pre>#Makefile command content<br><br>&lt;make command1 name&gt;:<br>          &lt;command1 instructions&gt;<br><br>&lt;make command2 name&gt;:<br>          &lt;command2 instructions&gt;<br><br>#etc...</pre><blockquote>Let’s do an example command via docker image creation.</blockquote><pre>## Builds images<br><br>build:<br> docker-compose build</pre><p>When running make commands from the terminal, the first “<strong><em>make”</em></strong> keyword is typed, followed by your <strong><em>“&lt;command name&gt;”</em></strong>. The above make command is run in terminal like this; “<strong><em>make build” </em></strong>.</p><p>Also, we can define dynamic variables in Makefile. If there are parts that are common to all of our commands or that I have changed according to the environment, we can use them for them.</p><pre># Dynamic variables<br>DOCKER_COMPOSE := docker-compose<br><br># Builds images<br>build:<br> $(DOCKER_COMPOSE) build<br><br># Sample of $@ usage. $@ is represent &quot;up&quot;. <br># Its value can be seen in terminal with the help of echo.<br>up:<br> @echo $@<br> $(DOCKER_COMPOSE) $@</pre><blockquote>Hint:<br>- When you run your command above example, you will see two lines output in terminal. First is your raw command and second is result of command. If it is not desired to see the executed command in the output, put the meat sign at the beginning of the command definition like; <em>“@docker-compose build” or “@$(DOCKER_COMPOSE) build” .<br>- </em>Also, if you want to use the command name in the command to be run, put “$@” in it. Like; <em>“@docker-compose $@” or “(DOCKER_COMPOSE) $@”</em></blockquote><p>If Docker compose and makefile were in the same directory, we could run it this way. Since it is in different directories, we will change it as follows.</p><pre># Dynamic variables<br>DOCKER_COMPOSE := docker-compose<br>COMPOSE_FILE_DEFAULT_NAME := docker-compose.yml<br>file := $(dir $(realpath $(MAKEFILE_LIST)))docker/$(COMPOSE_FILE_DEFAULT_NAME)<br><br># Build<br>build:<br> @$(DOCKER_COMPOSE) -f $(file) build<br><br># Up<br>up:<br> @$(DOCKER_COMPOSE) -f $(file) up<br><br># Down<br>down:<br> @$(DOCKER_COMPOSE) -f $(file) down<br><br># Restart<br>restart: down up</pre><p>We organized our command by defining the Docker compose file path to the <em>‘file’</em> variable. Again, we can run it by saying <em>‘make build’</em> and you can see the image creation from the terminal.</p><blockquote>Run multiple command at single line:<br>- We can now use a nice feature of this. Let’s create the image in one command and get it up and running like; Put and enter <em>“</em><strong><em>make build up</em></strong><em>” in terminal.<br>- </em>We can define other commands to a command as in the last command in the sample makefile above. <strong><em>“restart: down up” </em></strong>will kill your image first by down command then it will start. Put and enter <em>“</em><strong><em>make restart</em></strong><em>” in terminal.</em></blockquote><p><strong>In Conclusion<br> </strong>As you can see, make and makefile provide significant practicality in command management. It also gives efficiency and stability. You can use it in your various projects in local or deployment environments. I would also recommend looking at the reference.</p><p><strong>References</strong><br>- <a href="https://www.gnu.org/software/make/manual/make.html">https://www.gnu.org/software/make/manual/make.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b8292b4479" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Allow API request sending and testing from editor via HTTP Client]]></title>
            <link>https://medium.com/@emre.gok/allow-api-request-sending-and-testing-from-editor-via-http-client-803fcd6a301a?source=rss-e83923056ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/803fcd6a301a</guid>
            <category><![CDATA[rest-client]]></category>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[api-request]]></category>
            <category><![CDATA[api-documentation]]></category>
            <category><![CDATA[http-client]]></category>
            <dc:creator><![CDATA[Emre Gök]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 00:08:51 GMT</pubDate>
            <atom:updated>2023-06-15T11:08:24.584Z</atom:updated>
            <content:encoded><![CDATA[<p>I would like to talk about a plugin that I have experienced and used these days, which you can test quickly and easily through ide while developing your APIs. It can be an another alternative tool where you can generate, execute, and store information about API requests. It is called HTTP client in Jetbrain editors and REST client in VScode. The examples I will show in this article will be through VScode. Before I start, I would like to inform you file structure. HTTP request list laid up from <strong><em>.http</em></strong> or <strong><em>.rest</em></strong> files inside. The following example can be taken as a file of reference.</p><figure><img alt="sample of dot http, dot rest files" src="https://cdn-images-1.medium.com/max/280/1*FRA5fP_dAdRvorVY-SKDHQ.png" /><figcaption>View I. A file has been created with two different extension examples named <strong>tests</strong>.</figcaption></figure><p><strong>Method Declaration</strong><br>Firstly, I will give a sample for GET http method request. Thanks for dummyjson.com website to data providing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MSNj2MJfD5BOtxtpKFauSw.png" /><figcaption>View II. Sample for GET method for fetching product data and its response.</figcaption></figure><p>As seen above, we first give our method which is <em>“GET”</em>. Then we define the address where we will make the request and and press send request above. Also it can be send request with query string like below.</p><pre>GET https://dummyjson.com/products/search?q=shoes<br><br>//or (optional)<br><br>GET https://dummyjson.com/products/search<br>  ?q=shoes</pre><blockquote>Let’s send a <strong>POST</strong> request now:</blockquote><pre>POST https://dummyjson.com/products/add<br>Content-Type: application/json<br>Content-Length: 348<br><br>{ <br>    &quot;title&quot;: &quot;Black Product 1&quot;,<br>    &quot;description&quot;: &quot;Black product desc. 1&quot;<br>}</pre><p>If we would like to refer to the POST request structure, the header part is written line by line just below the request url. After leaving a space <em>(This part is important. If no space is left, the header will be perceived as content.)</em> After then body is written json, xml, graphql etc.</p><p><strong>Multiple Method Declaration<br></strong>Of course, we can define more than one http method because we create our api collection here. We can do this by putting three number-sign ‘<strong>###</strong>’ between methods.</p><figure><img alt="multiple http method declarations" src="https://cdn-images-1.medium.com/max/660/1*hY066zpFD9av5Nim9czc1A.png" /><figcaption>View III. Multiple HTTP request declaration</figcaption></figure><p><strong>Dynamic Variable Declaration<br></strong>When defining dynamic variables, the at sign<em>(‘@’) </em>is prefixed and then the value is written with an equal sign. When using, the variable name is written in double curly brackets<em>(‘{{&lt;variable_name&gt;}}’)</em>.</p><pre>#### sample.client.http<br><br>@domain = https://dummyjson.com<br>@query = q=shoes<br><br>GET {{domain}}/products/1<br><br>###<br><br>GET {{domain}}/products/search?{{query}}<br><br>###</pre><p><strong>Additional</strong><br>Comments can also be added to this file. A double forward slash (‘//’) can be used for comment lines. Http requests without Tls can be thrown like this; “<em>GET http://dummyjson.com/carts</em>”. You can find more in the references.</p><p><strong>References</strong><br>- <a href="https://marketplace.visualstudio.com/items?itemName=humao.rest-client">https://marketplace.visualstudio.com/items?itemName=humao.rest-client</a><br>- <a href="https://www.jetbrains.com/help/phpstorm/http-client-in-product-code-editor.html#run_request">https://www.jetbrains.com/help/phpstorm/http-client-in-product-code-editor.html#run_request</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=803fcd6a301a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Overview of Method Mocking in `Go`]]></title>
            <link>https://medium.com/@emre.gok/basic-overview-of-method-mocking-in-go-f27fba645bc1?source=rss-e83923056ba7------2</link>
            <guid isPermaLink="false">https://medium.com/p/f27fba645bc1</guid>
            <dc:creator><![CDATA[Emre Gök]]></dc:creator>
            <pubDate>Fri, 31 Mar 2023 02:05:37 GMT</pubDate>
            <atom:updated>2023-03-31T02:05:37.610Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Before I start, I would like to tell you the content of our topic. Writing the test in our code very important for improve the quality of code, doing less mistake, protect to unwanted changes and provide the documentation. Method mocking which is one of them is a method that often comes to our rescue. Firstly, we’ll write a unit test as normally. However, we’ll change the test by using mocking method later. In this section, we’ll focus on the changes made.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*eZ6l1IRgnqpimUGmx13yRg.jpeg" /><figcaption>let’s get the ball rolling!</figcaption></figure><h4>I. Creating Simple Sample Project for Standart Testing</h4><p>Let’s create a method in the main method where we pull the result and print it as changing its string type. This method takes two digits and sum them back.</p><p><strong>I.I</strong><em> Writing “main.go” codes</em></p><pre>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;strconv&quot;<br>)<br>  <br>func main() {<br>  result := displaySumAsString()<br><br>  fmt.Println(&quot;\nMerged data:&quot;, result)<br>  fmt.Printf(&quot;Type of result: %T\n&quot;, result)<br>}<br><br>func displaySumAsString() string {<br>  fmt.Println(&quot;Function: displaySumAsString&quot;)<br><br>  var digit1 int = 7<br>  var digit2 int = 11<br><br>  sum := getSum(digit1, digit2)<br><br>  return strconv.Itoa(sum)<br>}<br><br>func getSum(digit1 int, digit2 int) int {<br>  fmt.Println(&quot;Function: getSum&quot;)<br><br>  return digit1 + digit2<br>}</pre><blockquote>Output:</blockquote><blockquote>As can be seen from the output picture below, we got the sum(7+11) and type(string) as expected.</blockquote><figure><img alt="Base code result for standart unit test" src="https://cdn-images-1.medium.com/max/1004/1*zzxWH9UlfLjiicmUlqwx1Q.png" /><figcaption>Image 1. Base code result for standart unit test.</figcaption></figure><p><strong>I.II</strong><em> Writing “main_test.go” for unit test of getSum which is our target function</em></p><pre>package main<br><br>import (<br> &quot;strconv&quot;<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br>)<br><br>func TestDisplaySumAsString(t *testing.T) {<br> intSum := 18<br><br> actualSum := displaySumAsString()<br> expectedSum := strconv.Itoa(intSum)<br><br> assert.Equal(t, expectedSum, actualSum)<br>}</pre><blockquote>Output:</blockquote><blockquote>Also, we printed the currently running function name. We will use them later in evaluations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*sFkgZt18EWKKwOpvvqDyug.png" /><figcaption>Image 2. Result of standart unit test for displaySumAsString function.</figcaption></figure><p><strong>I.III</strong><em> Result Evaluation</em><br>In this attempt, unit test is run and make test assertions directly the related functions inside. We can prove that looking the printed function name. ‘Function: getSum’ text says us this. Following second section we’ll change this situation by using mocking.</p><h4>II. Change Current Project for Testing By Mocking Method</h4><p>The purpose of commissioning the interface here is to create a healthy working environment by separating the real method and the mocking method in the go code. Now, testify/mock package help us.</p><p><strong>II.I</strong><em> Modified target function which is </em><strong><em>getSum</em></strong><em> by interface</em></p><pre>package main<br><br>import (<br>  &quot;fmt&quot;<br>  &quot;strconv&quot;<br>)<br><br>type (<br>  summationInterface interface {<br>    getSum(int, int) (int)<br>  }<br><br>  MainStruct struct {<br>    SumI summationInterface<br>  }<br>)<br><br>func main() {<br>  result := MainStruct{SumI: new(MainStruct)}.displaySumAsString()<br><br>  fmt.Println(&quot;\nMerged data:&quot;, result)<br>  fmt.Printf(&quot;Type of result: %T\n&quot;, result)<br>}<br><br>func (mainS MainStruct) displaySumAsString() string {<br>  fmt.Println(&quot;Function: displaySumAsString&quot;)<br><br>  var digit1 int = 7<br>  var digit2 int = 11<br><br>  sum := mainS.SumI.getSum(digit1, digit2)<br><br>  return strconv.Itoa(sum)<br>}<br><br>func (mainS MainStruct) getSum(digit1 int, digit2 int) int {<br>  fmt.Println(&quot;Function: getSum&quot;)<br><br>  return digit1 + digit2<br>}</pre><blockquote>Output:</blockquote><blockquote><strong>displaySumAsString</strong> and <strong>getSum</strong> methods are covered by MainStruct object. In this way, we allow the ‘getSum’ method to be called by both the mock object and the real object. We manage it thanks to the <strong>summationInterface</strong> interface we have defined. The interface, which is the element of the <strong>MainStruct</strong> structure, will work according to the defined object.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1012/1*8hLaMQ3A_EWoHlmXjaiS4w.png" /><figcaption>Image 3. The result does not change after the interface change.</figcaption></figure><p><strong>II.II</strong><em> Mocking method in unit test</em></p><pre>package main<br><br>import (<br> &quot;strconv&quot;<br> &quot;testing&quot;<br><br> &quot;github.com/stretchr/testify/assert&quot;<br> &quot;github.com/stretchr/testify/mock&quot;<br>)<br><br>//Mock Interface<br>type SummationMockInterface struct {<br> mock.Mock<br>}<br><br>//Mock Method<br>func (sumMockI *SummationMockInterface) getSum(d1 int, d2 int) int {<br> arg := sumMockI.Called(d1, d2)<br> return arg.Get(0).(int)<br>}<br><br>func TestDisplaySumAsString(t *testing.T) {<br> intSum := 23<br><br> sumMockI := new(SummationMockInterface)<br> sumMockI.On(&quot;getSum&quot;, mock.Anything, mock.Anything).Return(intSum)<br><br> mainS := MainStruct{SumI: sumMockI}<br><br> actualSum := mainS.displaySumAsString()<br> expectedSum := strconv.Itoa(intSum)<br><br> assert.Equal(t, expectedSum, actualSum)<br>}</pre><blockquote>Output:</blockquote><blockquote>First of all, we need a shore that carries us testify mock package object. <br>For this reason, <strong>SummationMockInterface</strong> is created as struct type. A copy of the method is created from our original target(getSum), which we will use as a mock.<br><br>Here is one of the important, creating instance of SummationMockInterface and <br>the value to be returned is used with the “mock” packaging <strong>On</strong> method. After this declaration, the interface(<strong>SumI</strong>) is referenced to the wrapping structure object(<strong>mainS *MainStruct</strong>) for use in the displaySumAsString method.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*B2Y3EnXjYDI6myIhd0yDZg.png" /><figcaption>Image 4. It is seen that the mocking method does not work directly, it returns the given value in test function.</figcaption></figure><h4>Hint:</h4><ul><li>mock.Anything is used for our parameters.</li><li>sumMockI.Called(d1, d2) is represented our mocking method.</li><li>arg.Get(0).(int) tells us the return value type. (arg.Error(1) can be used to return an error)</li><li><em>VSCode</em> is used as <em>IDE</em> for development environment. Also, you can see below project folder structure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*n2otHR25VDiPzPHOV_rHyw.png" /><figcaption>Image 5. Reference for file structure example</figcaption></figure><p><strong>II.III</strong><em> Result Evaluation<br>As we can see </em>in the output picture above there is difference between first testing method and the second one. Only ‘Function: displaySumString’ text can be seen. This shows that only the copy of the mocked method works and returns the result we specified in the test. Inside the method did not work.</p><p><strong>III</strong> <em>Conclusion<br></em>As a result, by mocking methods, you can isolate systems, control them separately, and write tests that are independent of the code inside the method. In addition, it is recommended to take a look at <strong><em>mockgen</em></strong> and <strong><em>mockery</em></strong> packages.</p><p><strong>IV</strong> References<br><a href="https://pkg.go.dev/github.com/stretchr/testify/mock">https://pkg.go.dev/github.com/stretchr/testify/mock</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f27fba645bc1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>