<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>golang — StealthyCoder</title>
    <link>https://stealthycoder.writeas.com/tag:golang</link>
    <description>Making code ninjas out of everyone</description>
    <pubDate>Wed, 18 Nov 2026 20:10:04 +0000</pubDate>
    <item>
      <title>But can I write to it?</title>
      <link>https://stealthycoder.writeas.com/but-can-i-write-to-it?pk_campaign=rss-feed</link>
      <description>I just wanted to find out if a directory was writable for the user, and it turns out it is quite difficult to get that information in Golang. How difficult could it be?</description>
      <content:encoded><![CDATA[<p>I just wanted to find out if a directory was writable for the user, and it turns out it is quite difficult to get that information in Golang. How difficult could it be? </p>

<h2 id="stat-has-that-information">Stat has that information</h2>

<p>So my first inclination was that the <code>os.Stat</code> call has that information. It sort of does, in a way, but only for Linux. There is a <code>Sys()</code> method on the <code>fs.FileInfo</code> which returns a specific struct on Linux.</p>

<pre><code class="language-golang">package main

import (
	&#34;fmt&#34;
	&#34;os&#34;
	&#34;syscall&#34;
)

func main() {
	info, err := os.Stat(&#34;/tmp/some.file&#34;)
	if err != nil {
		fmt.Printf(&#34;%s&#34;, err)
	}
	if data, ok := info.Sys().(*syscall.Stat_t); ok {
		fmt.Printf(&#34;UID: %d\n&#34;, data.Uid)
	}
}
</code></pre>

<p>Is an example of how you get to that part and if you call <code>syscall.Getuid()</code> you can check it if they are the same and therefore if you at least own the resource. However that does not mean it is writable yet.</p>

<h2 id="permission-bit-logic">Permission bit logic</h2>

<p>I tried to finagle some bitwise logic with the permission bits, but again they only work on Linux and truth be told I never trusted myself that I got it to work.</p>

<h2 id="sidetrack-to-java">Sidetrack to Java</h2>

<p>So in Java there has been this <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isWritable(java.nio.file.Path)" rel="nofollow ugc">thing</a> since forever. You give it a path, and it tells you if it is writable. It is a static method and easy to use. Why does this not exist in Golang?!?!?</p>

<h2 id="solution">Solution</h2>

<p>So I did finally create a solution that was tailored for Unix and Windows separately.</p>

<h3 id="windows">Windows</h3>

<p>The Windows solution made me go down a rabbit hole, read up on Win32 API structs and methods on the Microsoft docs and dig deep down in the source of Go itself to figure out what I have access to. I will just show you the code:</p>

<pre><code class="language-golang">package main

import (
	&#34;fmt&#34;
	&#34;syscall&#34;
)

// https://learn.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants
const FILE_APPEND_FILE = 0x00000002

// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#parameters at dwShareMode
const FILE_LOCK = 0x00000000

func main() {
	// Checks if directory is writable
	if hwnd, err := syscall.CreateFile(syscall.StringToUTF16Ptr(&#34;C:\\Windows\\system32&#34;), FILE_APPEND_FILE, FILE_LOCK, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0); err == nil {
		if err = syscall.CloseHandle(hwnd); err != nil {
			fmt.Printf(&#34;%s\n&#34;, err)
		}
		fmt.Printf(&#34;This directory is writable&#34;)
	}
}
</code></pre>

<p>So yeah, a syscall to <code>CreateFile</code> to open a handle to a directory. I cannot figure out why you need to create a file to get a handle to be able to tell if you can write to a directory, even more so because <code>CreateDirectoryW</code> is also an actual call in the Win32 API, which is the only one that can actually create a directory. This is so confusing.</p>

<h3 id="linux-macosx">Linux / MacOSX</h3>

<p>The other solution was sort of similar but much easier. There is a nice syscall to Access.</p>

<pre><code class="language-golang">package main

import (
	&#34;fmt&#34;
	&#34;syscall&#34;
)

func main() {
	// Checks if directory is writable
	if err := syscall.Access(&#34;/opt/&#34;, syscall.O_RDWR); err == nil {
		fmt.Printf(&#34;This directory is writable&#34;)
	}
}
</code></pre>

<h1 id="conclusion">Conclusion</h1>

<p>I feel like all of this code can be hidden away in the Golang standard library and give us a nice <code>os.IsWritable(path string) bool</code> function signature for it.</p>

<p><a href="https://stealthycoder.writeas.com/tag:100DaysToOffload" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:golang" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">golang</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/but-can-i-write-to-it</guid>
      <pubDate>Wed, 04 Jan 2023 21:56:54 +0000</pubDate>
    </item>
    <item>
      <title>Twisted firestarter</title>
      <link>https://stealthycoder.writeas.com/twisted-firestarter?pk_campaign=rss-feed</link>
      <description>I was going down an avenue of seeing if we could implement a better and easier caching for Docker registry utilizing Google Firestore.</description>
      <content:encoded><![CDATA[<p>I was going down an avenue of seeing if we could implement a better and easier caching for Docker registry utilizing Google Firestore. </p>

<h2 id="getting-an-ember">Getting an ember</h2>

<p>Everyone that teaches to make/create your own fire will tell you that one of the most difficult things is getting an ember. A small hot enough material that will ignite the rest of the fuel. Well for me that was getting the source code for Docker registry (aka distribution) and getting it to compile and making sure I had the dependencies. They use an old school way using this tool called <a href="https://github.com/LK4D4/vndr" rel="nofollow ugc">vndr</a> which I am not familiar with since I am not an old school Golang developer.</p>

<p>After making sure the <code>vendor.conf</code> and <code>vndr</code> could play nicely and getting sucked down the rabbit hole of <code>GO111MODULE</code> to be switched off and what that does, in order to get my development environment to be able to follow the imports. So finally I have a somewhat working thing, but I cannot make changes yet. This actually brought back a memory of long ago trying to do some early Golang development. That is I like to separate out my dependencies and code. I think having a workspace of sorts that is your Git checkout and a whole separate other static dependency location is nice. For example, let us say you are working on two projects in Python.</p>

<p>One is your library you want to use and the other is a project utilizing that library. Then if you want to make a change to your library, you do not want to do it directly in the project utilizing the library. You would want to have changes being arbitrarily worked on for the library separate from the project utilizing it. On your machine you might have two Git folders, one the library and the other the project. Then the project might have a dependency file that imports the library. You could even specify the Git branch in there. So you make the changes to your library, commit and push to a new branch. Checkout a new branch in the project and update the dependency file to the new branch and see if it all works.</p>

<p>Then just having virtual environments makes the most sense to me as you do not want everyone to use the same version of something or have to be force to use the same version. I digress.</p>

<p>So since I have one folder that has my Git code, and another that is the dependency I thought I would do the naive thing and just clone the repo into where the dependency is currently held and work on the code with symlinks. Nope. That did not work. Then I tried to work directly in the dependency and that did not work.</p>

<p>At some point I just gave up on this and started to work without autocomplete, syntax highlighting and any IDE features whatsoever and just a glorified text editor is all I had.</p>

<h2 id="fanning-the-ember">Fanning the ember</h2>

<p>However small the ember, I needed to fan it in order to get the flame. Now I wanted to introduce the Firebase to our codebase that is sharing code with the Docker registry codebase. In essence we use it as a library as well. So in my project I just added the Firebase, no problem there. That took like 5 minutes. Then however came the problem that the Docker codebase had an old dependency on the GCP stuff. That messed things up. It caused a conflict I could not fix in our project codebase alone. So I had to update the GCP stuff for Docker registry (distribution codebase).</p>

<p>That meant just updating the reference right? Nope. I had to refactor the GCS storage layer as well with the newer calls and make them as close as I could to being backwards compatible/feature parity. Thinking I have done so, I try to recompile my code but it still does not use the new dependency I laid out. I just did a stupid thing and forked the code into my own Github, then changed all references to point to my Github instead of Docker. I since learned you can remap this in <code>go.mod</code> and probably also in <code>vendor.conf</code> but yeah. My hair already looked liked the Prodigy at this point so I might as well stay committed.</p>

<p>So I got a nice code base to work off of, and add my Firestore to our project using that augmented Docker codebase. Done, there is a flame going, starting to get bigger.</p>

<h2 id="fire-fire">Fire, fire</h2>

<p>Then I check the differences between this Firestore cache layer and our Redis one. It is tremendous, huge and insanely obvious what we should do after I answered the question if it is actually faster. Every call to the Firestore API to get a response takes a minimal of 1 second since that is the rate limit. So yeah, get the bucket of water and a bucket of sand to cover up this fire to put it out immediately.</p>

<p>Now I will say, we could improve our algorithm in the codebase and bypass how Docker gets tags by making one giant query and sending it to Firestore making it that we only pay a cost of 1 second once to get everything and it would be blazing fast afterwards since we would have everything and it would need to be kept in memory though. So it is still faster to query and store things in Redis.</p>

<p><a href="https://stealthycoder.writeas.com/tag:100DaysToOffload" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="https://stealthycoder.writeas.com/tag:docker" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">docker</span></a> <a href="https://stealthycoder.writeas.com/tag:golang" class="hashtag" rel="nofollow ugc"><span>#</span><span class="p-category">golang</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/twisted-firestarter</guid>
      <pubDate>Tue, 03 Jan 2023 09:12:02 +0000</pubDate>
    </item>
    <item>
      <title>Golang is quirky</title>
      <link>https://stealthycoder.writeas.com/golang-is-quirky?pk_campaign=rss-feed</link>
      <description>So recently I had the opportunity to make a proof of concept (PoC) in the Go language to share with some fellow developers. They are mostly Java developers and therefore I decided to make the PoC a MVC style REST API that returns JSON with a single Entity for now.</description>
      <content:encoded><![CDATA[<p>So recently I had the opportunity to make a proof of concept (PoC) in the Go language to share with some fellow developers. They are mostly Java developers and therefore I decided to make the PoC a MVC style REST API that returns JSON with a single Entity for now. </p>

<p>It does however store everything in a Postgresql database and features the full suite of HTTP verbs; GET, POST, PUT, PATCH and DELETE. With GET both returning the single entity and the list of all entities. I did not make pagination and transactions in the database part as it was not necessary for this PoC.</p>

<h1 id="syntax">Syntax</h1>

<p>The syntax still is quirky but now I know more of why it is the way it is. Everything that is Pascal case (meaning uppercase letters on the first words, ChocolateChipCookie for instance) will be public to other parts of the code. Everything that is camel cased (meaning the first letter is lowercase so chocolateChipCookie) will not be public to other parts of the code that exist in other packages. This explains a lot, as this way of making the formatting determine the accessibility levels shapes the way the code looks. This goes for methods, structs and anything else.</p>

<p>Not only do they need to be named as such, they also have to be foreseen of a comment. This I felt led to slowdown in the development cycle and a lot of redundant stupid comments that just annoyed me. If you name it Pascal case but no comment it will not be exported, which is the vernacular in Go to mean it is a public method. This also means that in a struct that will be used to return a response DTO you have to name everything with Pascal case and then use so called tags to shape the JSON data again.</p>

<h2 id="formatting">Formatting</h2>

<p>There is an auto formatting tool used on your code and it has to conform to that format otherwise you cannot compile. This is not too bad however if it conflicts with your own style then you have a problem.</p>

<h2 id="imports">Imports</h2>

<p>You cannot have unused imports and they will be removed automatically for you. This is quite annoying to say the least. I want to have the module imported in order to see what is inside it. This fights me on so many occasions. So you have to import something make a stupid variable to keep it around and look into it then.</p>

<h2 id="errors">Errors</h2>

<p>The error handling sucks. You have two extremes, <code>panic</code> and <code>Errors.New</code>. The <code>panic</code> stops the whole program, kind of like a segfault or Runtime exception in Java. The <code>Errors.New</code> has to bubble up through all the methods, so almost every method will return the data and the error. Then you have to manually check it. There is no problem with the following code:</p>

<pre><code class="language-go">⋮
data, _ := db.Find(&amp;fruit)
⋮
</code></pre>

<p>Which means you ignore the error and carry on which is not what you want maybe. It also means you can inadvertently do this, without realizing it and then get some weird errors in production.</p>

<h2 id="packages">Packages</h2>

<p>The packages are directory based only. So you can only have one package declared in one directory. You can have many files in one directory all belonging to the same package but the package is the identifier and not the file name like in Java. This required some getting used to. I also feel you miss some control somehow, as I ran into the fact I wanted to have a <code>entity</code> package but within it you will have all the entity straight by name. There does not exist a nested package where you type in <code>entity.fruit.Fruit</code> for example, then it will just be <code>fruit.Fruit</code> and it will come from the folder <code>entity/fruit/</code> for example. Under water you can have multiple naming of <code>fruit</code> just coming from different areas. I also inverted the naming, so making <code>fruit</code> carry all the different proponents like <code>service</code> and <code>dao</code> making it easier to deal with it.</p>

<h2 id="getting-started">Getting started</h2>

<p>The whole getting started is getting a <code>go.mod</code> file by executing <code>go mod init &lt;name&gt;</code> and then you are off. The only slight downside is you have to manage your own <code>GOPATH</code> environment variable to make a sort of working virtualenv like Python.</p>

<h2 id="idiomatic">Idiomatic</h2>

<p>There is no idiomatic way of writing Golang. There are rules for style and grammar and the like but they do not dictate how you write the overall architecture of the Golang application itself. It is difficult to get consistency across the ecosystem and therefore you get the same problem as in React for example and PHP as well. There will be subgroups and everyone is left to their own devices on how to do things.</p>

<p>That something is considered Pythonic is a good thing. There should optimally be only one clear way to do something. That means across the whole application and across the whole language ecosystem.</p>

<h1 id="classes-and-methods">Classes and methods</h1>

<p>There exists no such thing as a class in the Go language. What you do have are called <code>structs</code> and they can contain methods on them. So you construct the full class and methods and internal and external variables that are accessible by making a struct. A quick example of how to translate a class called <code>Message</code> with a constructor that takes in one argument called <code>msg</code> which is a string would be:</p>

<pre><code class="language-go">type Message struct {
    Msg string
}
</code></pre>

<p>To give that class the method <code>display</code> you would do the following:</p>

<pre><code class="language-go">
func (m *Message) Display() {
    fmt.Println(m.Msg)
}
</code></pre>

<p>There exists no such thing as <code>this</code> or <code>self</code> either, so you have to use the named way of adding methods to structs.</p>

<h1 id="things-left-to-be-discovered">Things left to be discovered</h1>

<p>The things I yet have to touch on and discover are the <em>goroutines</em> and the <em>channels</em>. These things I will uncover in a future post about CQRS where I will turn the following application into a CQRS one.</p>

<h1 id="the-poc-itself">The PoC itself</h1>

<p>So below is the PoC itself and the structure, there is not a lot going on as it is an easy application. I did try to get as much of the functionality in here of the Go language itself as that was the goal to showcase as much as possible.</p>

<pre><code>├── controllers
│   ├── controllers.go
│   └── fruit
│       └── fruit.go
├── dist
│   └── gin
├── docker-compose.yaml
├── Dockerfile
├── go.mod
├── go.sum
├── main.go
├── models
│   ├── dto
│   │   └── fruit.go
│   ├── entity
│   │   └── fruit.go
│   └── models.go
├── pkg
│   └── mod
│       └── cache
│           └── lock
├── router
│   └── router.go
└── services
    ├── dao
    │   ├── dao.go
    │   └── fruit
    │       └── fruit.go
    ├── fruit
    │   └── fruit.go
    └── services.go
</code></pre>

<p>The folders <code>dist</code> and <code>pkg</code> can be ignored for now. We will start with the <code>go.mod</code> one which contains the following.</p>

<pre><code>module pocs/go/gin

go 1.15

require (
    github.com/gin-gonic/gin v1.6.3
    github.com/google/uuid v1.1.1
    github.com/jinzhu/gorm v1.9.16
)

</code></pre>

<p>I named it gin too, which is mainly because that is the framework I used to make the web app this time. The last name of the whole thing is what Go will call it. Therefore there is a <code>gin</code> executable in the dist folder.</p>

<p>Then the <code>go.sum</code> is just there for the checksums. The <code>docker-compose.yaml</code> is there to help the devs out a bit more.</p>

<pre><code class="language-yaml">version: &#34;3.6&#34;

networks:
    gin_connect:
        name: &#34;gin_connect&#34;

services:
    gin:
        image: golang:1.15-alpine3.12
        container_name: gin.go.local
        env_file:
            - .env/app
        volumes:
          - .:/srv/http
        command: &#34;ash -c &#39;cd /srv/http &amp;&amp; go run --tags=jsoniter .&#39;&#34;
        depends_on:
            - db
        networks:
            - gin_connect
        stdin_open: true
        tty: true
        ports: 
            - 127.0.0.1:9999:8080
    db:
      image: postgres:13-alpine
      container_name: db.go.local
      environment:
        POSTGRES_PASSWORD: go
        POSTGRES_USER: go
        POSTGRES_DB: go
      stdin_open: true
      tty: true
      networks:
        - gin_connect
</code></pre>

<p>Then the <code>Dockerfile</code> is there to make the “actual” docker image that will be run in the cloud environments.</p>

<pre><code class="language-dockerfile">FROM golang:1.15-alpine3.12 as builder

COPY . /srv/http

RUN cd /srv/http &amp;&amp; go build --tags=jsoniter .

FROM alpine:3.12

COPY --from=builder /srv/http/dist/gin /app

CMD [&#34;/app&#34;]
</code></pre>

<h2 id="actual-code">Actual code</h2>

<p>So let us get into the actual code. This is what the <code>main.go</code> file looks like:</p>

<pre><code class="language-go">package main

import (
    &#34;pocs/go/gin/router&#34;
    &#34;pocs/go/gin/services&#34;
)

func main() {
    r := router.Router()
    services.SetupDatabase()
    r.Run() // listen and serve on 0.0.0.0:8080 (for windows &#34;localhost:8080&#34;)
}
</code></pre>

<p>Every Go application looks for one function called <strong>main</strong> in the <strong>main package</strong>. Packages are directory based so the root of this application is the main package. It just sets up the Router and the database. Also note that main is private as it is lowercased.</p>

<p>The <strong>router</strong> package is located in <code>router.go</code>.</p>

<pre><code class="language-go">package router

import (
    &#34;github.com/gin-gonic/gin&#34;
    &#34;pocs/go/gin/controllers&#34;
)

// Router sets up the complete routes from controllers and returns the full router
func Router() *gin.Engine {
    router := gin.Default()
    controllers.Init(router)
    return router
}
</code></pre>

<p>I chose to go the route of having the controllers package itself supply the routes by making each controller supply an Init method.</p>

<p>First the database though. It is in <code>services.go</code>.</p>

<pre><code class="language-go">package services

import (
    &#34;pocs/go/gin/models/entity&#34;
    &#34;pocs/go/gin/services/dao&#34;
)

// SetupDatabase makes sure all schemas are present
func SetupDatabase() {
    db := dao.Database()
    db.AutoMigrate(&amp;entity.Fruit{})
}
</code></pre>

<p>It just opens a connection to the database and does AutoMigrate for the one entity we have which makes sure the schema is there. This is a nice feature, but I have no idea how changes are managed yet.</p>

<p>Then the database comes from <code>dao.go</code>.</p>

<pre><code class="language-go">package dao

import (
    &#34;fmt&#34;
    &#34;os&#34;

    &#34;github.com/jinzhu/gorm&#34;
    _ &#34;github.com/jinzhu/gorm/dialects/postgres&#34; // Blank import for wrapping GORM
)

// Database returns a database connection
func Database() *gorm.DB {
    host, user, pass, dbname := os.Getenv(&#34;DB_HOST&#34;), os.Getenv(&#34;DB_USER&#34;), os.Getenv(&#34;DB_PASS&#34;), os.Getenv(&#34;DB_NAME&#34;)
    ssl := &#34;disable&#34;
    _, ok := os.LookupEnv(&#34;DB_SSL&#34;)
    if ok {
        ssl = &#34;require&#34;
    }
    db, err := gorm.Open(&#34;postgres&#34;, fmt.Sprintf(&#34;host=%s port=5432 user=%s dbname=%s password=%s sslmode=%s&#34;, host, user, dbname, pass, ssl))
    if err != nil {
        panic(err)
    }
    return db
}
</code></pre>

<p>This package just connects to the database. I have no idea yet if <code>gorm.Open</code> gives back a connection pool or that you just open and close and that underwater the open will just have a internal access to a connection pool. I have to delve into that one a bit more*. For now though it is just a PoC so this works for just one entity and no active users to one at most at a time.
<sub>*Found out the underlying mechanism and indeed one call to Open will return a connection pool.</sub></p>

<h2 id="models">Models</h2>

<p>Now that the database is out the way let us talk about the models. I use one Entity to represent the database records themselves and some DTOs. <code>models.go</code> just contains some empty package declaration. I created this as I was debugging the reason why it could not find my package. It turned out it was how I was calling it in the controller that was causing the issue. This file might be removed altogether.</p>

<pre><code class="language-go">package models
</code></pre>

<p>Then there is <code>fruit.go</code> inside entity.</p>

<pre><code class="language-go">package entity

import (
    &#34;time&#34;

    &#34;github.com/google/uuid&#34;
)

// Fruit represents the fruit in the database
type Fruit struct {
    ID        uuid.UUID
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
    Name      string
}
</code></pre>

<p>It just contains some standard stuff. The reason why <code>DeletedAt</code> is a pointer, is because then it can be <code>nil</code>. Standard GORM only supports integers as ids. This is a bad idea I feel, so therefore it is now a uuid. That does mean some manual action on certain actions, that is okay. Next up are the DTOs inside <code>fruit.go</code> in dto.</p>

<pre><code class="language-go">package dto

import (
    &#34;pocs/go/gin/models/entity&#34;
    &#34;github.com/google/uuid&#34;
)

// ReadFruit is the DTO for getting fruit at GET /fruit/:id
type ReadFruit struct {
    ID string `uri:&#34;id&#34; binding:&#34;required,uuid&#34;`
}

// CreateFruit is the DTO for creating new fruit at POST /fruit
type CreateFruit struct {
    Name string `json:&#34;name&#34; binding:&#34;required,max=255&#34;`
}

// UpdateFruit is the DTO for creating new fruit at POST /fruit
type UpdateFruit struct {
    Name string `json:&#34;name&#34; binding:&#34;required,max=255&#34;`
}

type metadata struct {
    CreatedAt int64 `json:&#34;created_at&#34; `
    UpdatedAt int64 `json:&#34;updated_at&#34; `
}

// ResponseFruit is the DTO for all responses
type ResponseFruit struct {
    ID       uuid.UUID `json:&#34;id&#34; `
    Name     string    `json:&#34;name&#34; `
    Metadata metadata  `json:&#34;metadata&#34; `
}

// Single creates a single ResponseFruit from a entity
func (res *ResponseFruit) Single(fruit entity.Fruit) *ResponseFruit {
    return &amp;ResponseFruit{ID: fruit.ID,
        Name: fruit.Name,
        Metadata: metadata{
            CreatedAt: fruit.CreatedAt.Unix(),
            UpdatedAt: fruit.UpdatedAt.Unix()}}
}

// Multi creates an array of responses
func (res *ResponseFruit) Multi(fruits ...*entity.Fruit) []*ResponseFruit {
    result := make([]*ResponseFruit, cap(fruits))
    for i := range fruits {
        fruit := fruits[i]
        result[i] = res.Single(*fruit)
    }
    return result
}
</code></pre>

<p>This contains the DTO necessary for holding certain bindings in order to utilize gin functions in the controller that will check if you supplied the correct data. These occur in the form of so called tags. These are the string after the type declaration inside the struct. Then I added two helper methods, <code>Single</code> and <code>Multi</code> . They take in a entity and convert them into a <code>ResponseFruit</code> DTO. The ... means a variadic input, so it can be 0,1 or any other whole positive integer.</p>

<h2 id="controllers">Controllers</h2>

<p>The controllers start with the uniform entry point in <code>controllers.go</code>.</p>

<pre><code class="language-go">package controllers

import (
    &#34;github.com/gin-gonic/gin&#34;
    &#34;pocs/go/gin/controllers/fruit&#34;
)

// Init takes router and calls all subsequent init methods
func Init(router *gin.Engine) {
    fruit.Init(router)
}
</code></pre>

<p>This will be extended on later of course. Then the only one we have right now is <code>fruit.go</code> inside of the controllers.</p>

<pre><code class="language-go">package fruit

import (
    &#34;net/http&#34;
    &#34;reflect&#34;

    &#34;github.com/gin-gonic/gin&#34;
    &#34;pocs/go/gin/models/dto&#34;
    &#34;pocs/go/gin/services/fruit&#34;
    &#34;github.com/google/uuid&#34;
)

// Init takes router and adds the necessary routes to it
func Init(router *gin.Engine) {
    group := router.Group(&#34;/fruit&#34;)
    {
        group.GET(&#34;/&#34;, listHandler)
        group.GET(&#34;/:id&#34;, getHandler)
        group.POST(&#34;/&#34;, postHandler)
        group.PATCH(&#34;/:id&#34;, patchHandler)
        group.PUT(&#34;/:id&#34;, putHandler)
        group.DELETE(&#34;/:id&#34;, deleteHandler)
    }
}

var service = &amp;fruit.Service{}

var listHandler = func(c *gin.Context) {
    fruits, err := service.FindAll()
    if err != nil {
        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    var res = dto.ResponseFruit{}
    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Multi(fruits...)})
}

var getHandler = func(c *gin.Context) {
    var req dto.ReadFruit
    if err := c.ShouldBindUri(&amp;req); err != nil {
        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    fruit, err := service.Find(uuid.MustParse(req.ID))
    if err != nil {
        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    var res = dto.ResponseFruit{}
    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(*fruit)})
}

var postHandler = func(c *gin.Context) {
    var req dto.CreateFruit
    if err := c.ShouldBindJSON(&amp;req); err != nil {
        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    fruit, err := service.Create(req.Name)
    if err != nil {
        c.SecureJSON(http.StatusInternalServerError, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    var res = dto.ResponseFruit{}
    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(*fruit)})
}

var patchHandler = func(c *gin.Context) {
    var uriCheck dto.ReadFruit
    var reqBodyCheck dto.UpdateFruit
    if err := c.ShouldBindUri(&amp;uriCheck); err != nil {
        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    if err := c.ShouldBindJSON(&amp;reqBodyCheck); err != nil {
        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    obj, err := service.Find(uuid.MustParse(uriCheck.ID))
    if err != nil {
        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    elem := reflect.ValueOf(&amp;reqBodyCheck).Elem()
    typeOf := elem.Type()
    for i := 0; i &lt; elem.NumField(); i++ {
        f := elem.Field(i)
        v := reflect.ValueOf(obj).Elem().FieldByName(typeOf.Field(i).Name)
        if v.IsValid() {
            v.Set(f)
        }

    }

    fruit, err := service.Update(*obj)
    if err != nil {
        c.SecureJSON(http.StatusInternalServerError, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    var res = dto.ResponseFruit{}
    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(*fruit)})
}

var putHandler = patchHandler

var deleteHandler = func(c *gin.Context) {
    var req dto.ReadFruit
    if err := c.ShouldBindUri(&amp;req); err != nil {
        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    _, err := service.Delete(uuid.MustParse(req.ID))
    if err != nil {
        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})
        return
    }
    c.SecureJSON(http.StatusNoContent, nil)
}

</code></pre>

<p>There is a lot of repetition. So for the future I would definitely want to utilize some compression oriented programming and take those out into more private methods.</p>

<h2 id="services">Services</h2>

<p>Then we get to the service in <code>fruit.go</code> inside services/fruit.</p>

<pre><code class="language-go">package fruit

import (
	&#34;pocs/go/gin/models/entity&#34;
	&#34;pocs/go/gin/services/dao/fruit&#34;
	&#34;github.com/google/uuid&#34;
)

// Service is there to hold everything and have multiple copies
type Service struct {
}

var dao = &amp;fruit.DAO{}

// Find gives back the Fruit with given uuid if it exists
func (s *Service) Find(id uuid.UUID) (*entity.Fruit, error) {
	return dao