<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>golang &amp;mdash; StealthyCoder</title>
    <link>https://stealthycoder.writeas.com/tag:golang</link>
    <description>Making code ninjas out of everyone</description>
    <pubDate>Wed, 29 Apr 2026 05:41:25 +0000</pubDate>
    <item>
      <title>Golang is quirky</title>
      <link>https://stealthycoder.writeas.com/golang-is-quirky?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[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. !--more--&#xA;&#xA;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. &#xA;&#xA;Syntax&#xA;&#xA;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. &#xA;&#xA;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. &#xA;&#xA;Formatting&#xA;&#xA;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.&#xA;&#xA;Imports&#xA;&#xA;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. &#xA;&#xA;Errors&#xA;&#xA;The error handling sucks. You have two extremes, panic and Errors.New. The panic stops the whole program, kind of like a segfault or Runtime exception in Java. The Errors.New 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:&#xA;&#xA;⋮&#xA;data,  := db.Find(&amp;fruit)&#xA;⋮&#xA;&#xA;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. &#xA;&#xA;Packages&#xA;&#xA;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 entity package but within it you will have all the entity straight by name. There does not exist a nested package where you type in entity.fruit.Fruit for example, then it will just be fruit.Fruit and it will come from the folder entity/fruit/ for example. Under water you can have multiple naming of fruit just coming from different areas. I also inverted the naming, so making fruit carry all the different proponents like service and dao making it easier to deal with it. &#xA;&#xA;Getting started&#xA;&#xA;The whole getting started is getting a go.mod file by executing go mod init name and then you are off. The only slight downside is you have to manage your own GOPATH environment variable to make a sort of working virtualenv like Python.&#xA;&#xA;Idiomatic&#xA;&#xA;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. &#xA;&#xA;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. &#xA;&#xA;Classes and methods&#xA;&#xA;There exists no such thing as a class in the Go language. What you do have are called structs 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 Message with a constructor that takes in one argument called msg which is a string would be:&#xA;&#xA;type Message struct {&#xA;    Msg string&#xA;}&#xA;To give that class the method display you would do the following:&#xA;&#xA;func (m Message) Display() {&#xA;    fmt.Println(m.Msg)&#xA;}&#xA;&#xA;There exists no such thing as this or self either, so you have to use the named way of adding methods to structs. &#xA;&#xA;Things left to be discovered&#xA;&#xA;The things I yet have to touch on and discover are the goroutines and the channels. These things I will uncover in a future post about CQRS where I will turn the following application into a CQRS one. &#xA;&#xA;The PoC itself&#xA;&#xA;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. &#xA;&#xA;├── controllers&#xA;│   ├── controllers.go&#xA;│   └── fruit&#xA;│       └── fruit.go&#xA;├── dist&#xA;│   └── gin&#xA;├── docker-compose.yaml&#xA;├── Dockerfile&#xA;├── go.mod&#xA;├── go.sum&#xA;├── main.go&#xA;├── models&#xA;│   ├── dto&#xA;│   │   └── fruit.go&#xA;│   ├── entity&#xA;│   │   └── fruit.go&#xA;│   └── models.go&#xA;├── pkg&#xA;│   └── mod&#xA;│       └── cache&#xA;│           └── lock&#xA;├── router&#xA;│   └── router.go&#xA;└── services&#xA;    ├── dao&#xA;    │   ├── dao.go&#xA;    │   └── fruit&#xA;    │       └── fruit.go&#xA;    ├── fruit&#xA;    │   └── fruit.go&#xA;    └── services.go&#xA;The folders dist and pkg can be ignored for now. We will start with the go.mod one which contains the following.&#xA;&#xA;module pocs/go/gin&#xA;&#xA;go 1.15&#xA;&#xA;require (&#xA;    github.com/gin-gonic/gin v1.6.3&#xA;    github.com/google/uuid v1.1.1&#xA;    github.com/jinzhu/gorm v1.9.16&#xA;)&#xA;&#xA;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 gin executable in the dist folder. &#xA;&#xA;Then the go.sum is just there for the checksums. The docker-compose.yaml is there to help the devs out a bit more. &#xA;&#xA;version: &#34;3.6&#34;&#xA;&#xA;networks:&#xA;    ginconnect:&#xA;        name: &#34;ginconnect&#34;&#xA;&#xA;services:&#xA;    gin:&#xA;        image: golang:1.15-alpine3.12&#xA;        containername: gin.go.local&#xA;        envfile:&#xA;            .env/app&#xA;        volumes:&#xA;          .:/srv/http&#xA;        command: &#34;ash -c &#39;cd /srv/http &amp;&amp; go run --tags=jsoniter .&#39;&#34;&#xA;        dependson:&#xA;            db&#xA;        networks:&#xA;            ginconnect&#xA;        stdinopen: true&#xA;        tty: true&#xA;        ports: &#xA;            127.0.0.1:9999:8080&#xA;    db:&#xA;      image: postgres:13-alpine&#xA;      containername: db.go.local&#xA;      environment:&#xA;        POSTGRESPASSWORD: go&#xA;        POSTGRESUSER: go&#xA;        POSTGRESDB: go&#xA;      stdinopen: true&#xA;      tty: true&#xA;      networks:&#xA;        ginconnect&#xA;Then the Dockerfile is there to make the &#34;actual&#34; docker image that will be run in the cloud environments. &#xA;&#xA;FROM golang:1.15-alpine3.12 as builder&#xA;&#xA;COPY . /srv/http&#xA;&#xA;RUN cd /srv/http &amp;&amp; go build --tags=jsoniter .&#xA;&#xA;FROM alpine:3.12&#xA;&#xA;COPY --from=builder /srv/http/dist/gin /app&#xA;&#xA;CMD [&#34;/app&#34;]&#xA;Actual code&#xA;&#xA;So let us get into the actual code. This is what the main.go file looks like:&#xA;&#xA;package main&#xA;&#xA;import (&#xA;    &#34;pocs/go/gin/router&#34;&#xA;    &#34;pocs/go/gin/services&#34;&#xA;)&#xA;&#xA;func main() {&#xA;    r := router.Router()&#xA;    services.SetupDatabase()&#xA;    r.Run() // listen and serve on 0.0.0.0:8080 (for windows &#34;localhost:8080&#34;)&#xA;}&#xA;&#xA;Every Go application looks for one function called main in the main package. 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.   &#xA;&#xA;The router package is located in router.go. &#xA;&#xA;package router&#xA;&#xA;import (&#xA;    &#34;github.com/gin-gonic/gin&#34;&#xA;    &#34;pocs/go/gin/controllers&#34;&#xA;)&#xA;&#xA;// Router sets up the complete routes from controllers and returns the full router&#xA;func Router() gin.Engine {&#xA;    router := gin.Default()&#xA;    controllers.Init(router)&#xA;    return router&#xA;}&#xA;I chose to go the route of having the controllers package itself supply the routes by making each controller supply an Init method. &#xA;&#xA;First the database though. It is in services.go.&#xA;&#xA;package services&#xA;&#xA;import (&#xA;    &#34;pocs/go/gin/models/entity&#34;&#xA;    &#34;pocs/go/gin/services/dao&#34;&#xA;)&#xA;&#xA;// SetupDatabase makes sure all schemas are present&#xA;func SetupDatabase() {&#xA;    db := dao.Database()&#xA;    db.AutoMigrate(&amp;entity.Fruit{})&#xA;}&#xA;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. &#xA;&#xA;Then the database comes from dao.go.&#xA;&#xA;package dao&#xA;&#xA;import (&#xA;    &#34;fmt&#34;&#xA;    &#34;os&#34;&#xA;&#xA;    &#34;github.com/jinzhu/gorm&#34;&#xA;     &#34;github.com/jinzhu/gorm/dialects/postgres&#34; // Blank import for wrapping GORM&#xA;)&#xA;&#xA;// Database returns a database connection&#xA;func Database() gorm.DB {&#xA;    host, user, pass, dbname := os.Getenv(&#34;DBHOST&#34;), os.Getenv(&#34;DBUSER&#34;), os.Getenv(&#34;DBPASS&#34;), os.Getenv(&#34;DBNAME&#34;)&#xA;    ssl := &#34;disable&#34;&#xA;    , ok := os.LookupEnv(&#34;DBSSL&#34;)&#xA;    if ok {&#xA;        ssl = &#34;require&#34;&#xA;    }&#xA;    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))&#xA;    if err != nil {&#xA;        panic(err)&#xA;    }&#xA;    return db&#xA;}&#xA;This package just connects to the database. I have no idea yet if gorm.Open 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. &#xA;sub\Found out the underlying mechanism and indeed one call to Open will return a connection pool./sub&#xA;&#xA;Models&#xA;&#xA;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. models.go 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. &#xA;&#xA;package models&#xA;&#xA;Then there is fruit.go inside entity. &#xA;&#xA;package entity&#xA;&#xA;import (&#xA;    &#34;time&#34;&#xA;&#xA;    &#34;github.com/google/uuid&#34;&#xA;)&#xA;&#xA;// Fruit represents the fruit in the database&#xA;type Fruit struct {&#xA;    ID        uuid.UUID&#xA;    CreatedAt time.Time&#xA;    UpdatedAt time.Time&#xA;    DeletedAt time.Time&#xA;    Name      string&#xA;}&#xA;It just contains some standard stuff. The reason why DeletedAt is a pointer, is because then it can be nil. 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 fruit.go in dto. &#xA;&#xA;package dto&#xA;&#xA;import (&#xA;    &#34;pocs/go/gin/models/entity&#34;&#xA;    &#34;github.com/google/uuid&#34;&#xA;)&#xA;&#xA;// ReadFruit is the DTO for getting fruit at GET /fruit/:id&#xA;type ReadFruit struct {&#xA;    ID string uri:&#34;id&#34; binding:&#34;required,uuid&#34;&#xA;}&#xA;&#xA;// CreateFruit is the DTO for creating new fruit at POST /fruit&#xA;type CreateFruit struct {&#xA;    Name string json:&#34;name&#34; binding:&#34;required,max=255&#34;&#xA;}&#xA;&#xA;// UpdateFruit is the DTO for creating new fruit at POST /fruit&#xA;type UpdateFruit struct {&#xA;    Name string json:&#34;name&#34; binding:&#34;required,max=255&#34;&#xA;}&#xA;&#xA;type metadata struct {&#xA;    CreatedAt int64 json:&#34;createdat&#34; &#xA;    UpdatedAt int64 json:&#34;updatedat&#34; &#xA;}&#xA;&#xA;// ResponseFruit is the DTO for all responses&#xA;type ResponseFruit struct {&#xA;    ID       uuid.UUID json:&#34;id&#34; &#xA;    Name     string    json:&#34;name&#34; &#xA;    Metadata metadata  json:&#34;metadata&#34; &#xA;}&#xA;&#xA;// Single creates a single ResponseFruit from a entity&#xA;func (res ResponseFruit) Single(fruit entity.Fruit) ResponseFruit {&#xA;    return &amp;ResponseFruit{ID: fruit.ID,&#xA;        Name: fruit.Name,&#xA;        Metadata: metadata{&#xA;            CreatedAt: fruit.CreatedAt.Unix(),&#xA;            UpdatedAt: fruit.UpdatedAt.Unix()}}&#xA;}&#xA;&#xA;// Multi creates an array of responses&#xA;func (res ResponseFruit) Multi(fruits ...entity.Fruit) []ResponseFruit {&#xA;    result := make([]ResponseFruit, cap(fruits))&#xA;    for i := range fruits {&#xA;        fruit := fruits[i]&#xA;        result[i] = res.Single(fruit)&#xA;    }&#xA;    return result&#xA;}&#xA;&#xA;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, Single and Multi . They take in a entity and convert them into a ResponseFruit DTO. The ... means a variadic input, so it can be 0,1 or any other whole positive integer. &#xA;&#xA;Controllers &#xA;&#xA;The controllers start with the uniform entry point in controllers.go.&#xA;&#xA;package controllers&#xA;&#xA;import (&#xA;    &#34;github.com/gin-gonic/gin&#34;&#xA;    &#34;pocs/go/gin/controllers/fruit&#34;&#xA;)&#xA;&#xA;// Init takes router and calls all subsequent init methods&#xA;func Init(router gin.Engine) {&#xA;    fruit.Init(router)&#xA;}&#xA;&#xA;This will be extended on later of course. Then the only one we have right now is fruit.go inside of the controllers. &#xA;&#xA;package fruit&#xA;&#xA;import (&#xA;    &#34;net/http&#34;&#xA;    &#34;reflect&#34;&#xA;&#xA;    &#34;github.com/gin-gonic/gin&#34;&#xA;    &#34;pocs/go/gin/models/dto&#34;&#xA;    &#34;pocs/go/gin/services/fruit&#34;&#xA;    &#34;github.com/google/uuid&#34;&#xA;)&#xA;&#xA;// Init takes router and adds the necessary routes to it&#xA;func Init(router gin.Engine) {&#xA;    group := router.Group(&#34;/fruit&#34;)&#xA;    {&#xA;        group.GET(&#34;/&#34;, listHandler)&#xA;        group.GET(&#34;/:id&#34;, getHandler)&#xA;        group.POST(&#34;/&#34;, postHandler)&#xA;        group.PATCH(&#34;/:id&#34;, patchHandler)&#xA;        group.PUT(&#34;/:id&#34;, putHandler)&#xA;        group.DELETE(&#34;/:id&#34;, deleteHandler)&#xA;    }&#xA;}&#xA;&#xA;var service = &amp;fruit.Service{}&#xA;&#xA;var listHandler = func(c gin.Context) {&#xA;    fruits, err := service.FindAll()&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    var res = dto.ResponseFruit{}&#xA;    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Multi(fruits...)})&#xA;}&#xA;&#xA;var getHandler = func(c gin.Context) {&#xA;    var req dto.ReadFruit&#xA;    if err := c.ShouldBindUri(&amp;req); err != nil {&#xA;        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    fruit, err := service.Find(uuid.MustParse(req.ID))&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    var res = dto.ResponseFruit{}&#xA;    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(fruit)})&#xA;}&#xA;&#xA;var postHandler = func(c gin.Context) {&#xA;    var req dto.CreateFruit&#xA;    if err := c.ShouldBindJSON(&amp;req); err != nil {&#xA;        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    fruit, err := service.Create(req.Name)&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusInternalServerError, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    var res = dto.ResponseFruit{}&#xA;    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(fruit)})&#xA;}&#xA;&#xA;var patchHandler = func(c gin.Context) {&#xA;    var uriCheck dto.ReadFruit&#xA;    var reqBodyCheck dto.UpdateFruit&#xA;    if err := c.ShouldBindUri(&amp;uriCheck); err != nil {&#xA;        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    if err := c.ShouldBindJSON(&amp;reqBodyCheck); err != nil {&#xA;        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    obj, err := service.Find(uuid.MustParse(uriCheck.ID))&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    elem := reflect.ValueOf(&amp;reqBodyCheck).Elem()&#xA;    typeOf := elem.Type()&#xA;    for i := 0; i &lt; elem.NumField(); i++ {&#xA;        f := elem.Field(i)&#xA;        v := reflect.ValueOf(obj).Elem().FieldByName(typeOf.Field(i).Name)&#xA;        if v.IsValid() {&#xA;            v.Set(f)&#xA;        }&#xA;&#xA;    }&#xA;&#xA;    fruit, err := service.Update(obj)&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusInternalServerError, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    var res = dto.ResponseFruit{}&#xA;    c.SecureJSON(http.StatusOK, gin.H{&#34;data&#34;: res.Single(fruit)})&#xA;}&#xA;&#xA;var putHandler = patchHandler&#xA;&#xA;var deleteHandler = func(c gin.Context) {&#xA;    var req dto.ReadFruit&#xA;    if err := c.ShouldBindUri(&amp;req); err != nil {&#xA;        c.SecureJSON(http.StatusBadRequest, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    , err := service.Delete(uuid.MustParse(req.ID))&#xA;    if err != nil {&#xA;        c.SecureJSON(http.StatusNotFound, gin.H{&#34;msg&#34;: err.Error()})&#xA;        return&#xA;    }&#xA;    c.SecureJSON(http.StatusNoContent, nil)&#xA;}&#xA;&#xA;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. &#xA;&#xA;Services&#xA;&#xA;Then we get to the service in fruit.go inside services/fruit. &#xA;&#xA;package fruit&#xA;&#xA;import (&#xA;&#x9;&#34;pocs/go/gin/models/entity&#34;&#xA;&#x9;&#34;pocs/go/gin/services/dao/fruit&#34;&#xA;&#x9;&#34;github.com/google/uuid&#34;&#xA;)&#xA;&#xA;// Service is there to hold everything and have multiple copies&#xA;type Service struct {&#xA;}&#xA;&#xA;var dao = &amp;fruit.DAO{}&#xA;&#xA;// Find gives back the Fruit with given uuid if it exists&#xA;func (s Service) Find(id uuid.UUID) (entity.Fruit, error) {&#xA;&#x9;return dao.FindByID(id)&#xA;}&#xA;&#xA;// FindAll gives back the Fruit with given uuid if it exists&#xA;func (s Service) FindAll() ([]entity.Fruit, error) {&#xA;&#x9;return dao.Find()&#xA;}&#xA;&#xA;// Create will assign random uuid and set createdAt date&#xA;func (s Service) Create(name string) (entity.Fruit, error) {&#xA;&#x9;fruit := entity.Fruit{Name: name, ID: uuid.New()}&#xA;&#xA;&#x9;return dao.Insert(fruit)&#xA;}&#xA;&#xA;// Update updates the resource if it can find it&#xA;func (s Service) Update(fruit entity.Fruit) (entity.Fruit, error) {&#xA;&#xA;&#x9;return dao.Update(fruit)&#xA;}&#xA;&#xA;// Delete soft deletes the record&#xA;func (s Service) Delete(id uuid.UUID) (entity.Fruit, error) {&#xA;&#x9;var fruit = entity.Fruit{}&#xA;&#x9;fruit.ID = id&#xA;&#x9;return dao.Delete(fruit)&#xA;}&#xA;&#xA;Just a bunch of helper methods for doing CRUD. Then I also made a DAO layer just to help out the Java devs a bit more. It is inside fruit.go in services/dao/fruit. &#xA;&#xA;package fruit&#xA;&#xA;import (&#xA;&#x9;&#34;fmt&#34;&#xA;&#xA;&#x9;&#34;pocs/go/gin/models/entity&#34;&#xA;&#x9;&#34;pocs/go/gin/services/dao&#34;&#xA;&#x9;&#34;github.com/google/uuid&#34;&#xA;)&#xA;&#xA;// DAO struct that will hold the methods for doing DAO stuff&#xA;type DAO struct {&#xA;}&#xA;&#xA;var db = dao.Database()&#xA;&#xA;// Find gets all fruits without pagination&#xA;func (DAO) Find() ([]entity.Fruit, error) {&#xA;&#x9;var fruits []entity.Fruit&#xA;&#x9;result := db.Find(&amp;fruits)&#xA;&#x9;if result.Error != nil {&#xA;&#x9;&#x9;return nil, result.Error&#xA;&#x9;}&#xA;&#x9;return fruits, nil&#xA;}&#xA;&#xA;// FindByID helper method to call internal find method&#xA;func (DAO) FindByID(id uuid.UUID) (entity.Fruit, error) {&#xA;&#x9;fruit := entity.Fruit{}&#xA;&#x9;result := db.Where(&#34;id = ?&#34;, id.String()).First(&amp;fruit)&#xA;&#x9;if result.RecordNotFound() {&#xA;&#x9;&#x9;return nil, fmt.Errorf(&#34;Fruit with id: %s does not exist&#34;, id)&#xA;&#x9;}&#xA;&#x9;return &amp;fruit, nil&#xA;}&#xA;&#xA;// Insert will insert record&#xA;func (d DAO) Insert(fruit entity.Fruit) (entity.Fruit, error) {&#xA;&#x9;result := db.Create(&amp;fruit)&#xA;&#x9;if result.Error != nil {&#xA;&#x9;&#x9;return nil, result.Error&#xA;&#x9;}&#xA;&#x9;return d.FindByID(fruit.ID)&#xA;}&#xA;&#xA;// Update will update the record in the database&#xA;func (d DAO) Update(fruit entity.Fruit) (entity.Fruit, error) {&#xA;&#xA;&#x9;result := db.Save(&amp;fruit)&#xA;&#x9;if result.Error != nil {&#xA;&#x9;&#x9;return nil, result.Error&#xA;&#x9;}&#xA;&#xA;&#x9;return d.FindByID(fruit.ID)&#xA;}&#xA;&#xA;// Delete will soft delete the record in the database&#xA;func (d DAO) Delete(fruit entity.Fruit) (*entity.Fruit, error) {&#xA;&#xA;&#x9;_, err := d.FindByID(fruit.ID)&#xA;&#x9;if err != nil {&#xA;&#x9;&#x9;return nil, err&#xA;&#x9;}&#xA;&#x9;result := db.Delete(&amp;fruit)&#xA;&#x9;if result.Error != nil {&#xA;&#x9;&#x9;return nil, result.Error&#xA;&#x9;}&#xA;&#x9;db.Unscoped().Find(&amp;fruit)&#xA;&#xA;&#x9;return &amp;fruit, nil&#xA;}&#xA;&#xA;The reason the extra FindByID calls occur are because the Save and Create methods from GORM do not update the actual representation sent in, that only occurs with the Find method. By default Find will not look for soft deleted records, therefore the Delete uses the Unscoped variant. The Service and DAO layers are consistent in that they all return the entity but I just do not do anything with it in the controller for the DELETE verb. &#xA;&#xA;Conclusions&#xA;&#xA;That is it for the PoC. Just a simple application that hopefully showcases the Go language. It is quirky at times but you get used to it and also there exist enough good libraries out there that you can use to make web application dev possible. I do think it is best used for the things it is being used for right now, which is to make CLI tools that will run everywhere. Like Docker and Kubernetes as well as a webserver called Caddy that can run anywhere. &#xA;&#xA;The thing that I dislike the most is the error handling, or lack thereof. It feels very janky that you have to manually check and bubble errors all over the place. Almost every method returns the error again. This means it is quite cumbersome and you keep writing the same code over and over again. &#xA;&#xA;Also the structure of the Go application is a bit arbitrary, so you can go all out like I did here or just put it all together and keep things as private as possible everywhere. I think this is just all preference and you should make good agreements within the team on what will be the way forward.&#xA;&#xA;#code #golang]]&gt;</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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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" 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.FindByID(id)
}

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

// Create will assign random uuid and set createdAt date
func (s *Service) Create(name string) (*entity.Fruit, error) {
	fruit := entity.Fruit{Name: name, ID: uuid.New()}

	return dao.Insert(fruit)
}

// Update updates the resource if it can find it
func (s *Service) Update(fruit entity.Fruit) (*entity.Fruit, error) {

	return dao.Update(fruit)
}

// Delete soft deletes the record
func (s *Service) Delete(id uuid.UUID) (*entity.Fruit, error) {
	var fruit = entity.Fruit{}
	fruit.ID = id
	return dao.Delete(fruit)
}

</code></pre>

<p>Just a bunch of helper methods for doing CRUD. Then I also made a DAO layer just to help out the Java devs a bit more. It is inside <code>fruit.go</code> in services/dao/fruit.</p>

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

import (
	&#34;fmt&#34;

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

// DAO struct that will hold the methods for doing DAO stuff
type DAO struct {
}

var db = dao.Database()

// Find gets all fruits without pagination
func (DAO) Find() ([]*entity.Fruit, error) {
	var fruits []*entity.Fruit
	result := db.Find(&amp;fruits)
	if result.Error != nil {
		return nil, result.Error
	}
	return fruits, nil
}

// FindByID helper method to call internal find method
func (DAO) FindByID(id uuid.UUID) (*entity.Fruit, error) {
	fruit := entity.Fruit{}
	result := db.Where(&#34;id = ?&#34;, id.String()).First(&amp;fruit)
	if result.RecordNotFound() {
		return nil, fmt.Errorf(&#34;Fruit with id: %s does not exist&#34;, id)
	}
	return &amp;fruit, nil
}

// Insert will insert record
func (d *DAO) Insert(fruit entity.Fruit) (*entity.Fruit, error) {
	result := db.Create(&amp;fruit)
	if result.Error != nil {
		return nil, result.Error
	}
	return d.FindByID(fruit.ID)
}

// Update will update the record in the database
func (d *DAO) Update(fruit entity.Fruit) (*entity.Fruit, error) {

	result := db.Save(&amp;fruit)
	if result.Error != nil {
		return nil, result.Error
	}

	return d.FindByID(fruit.ID)
}

// Delete will soft delete the record in the database
func (d *DAO) Delete(fruit entity.Fruit) (*entity.Fruit, error) {

	_, err := d.FindByID(fruit.ID)
	if err != nil {
		return nil, err
	}
	result := db.Delete(&amp;fruit)
	if result.Error != nil {
		return nil, result.Error
	}
	db.Unscoped().Find(&amp;fruit)

	return &amp;fruit, nil
}

</code></pre>

<p>The reason the extra <code>FindByID</code> calls occur are because the <code>Save</code> and <code>Create</code> methods from GORM do not update the actual representation sent in, that only occurs with the <code>Find</code> method. By default <code>Find</code> will not look for soft deleted records, therefore the <code>Delete</code> uses the <code>Unscoped</code> variant. The Service and DAO layers are consistent in that they all return the entity but I just do not do anything with it in the controller for the <code>DELETE</code> verb.</p>

<h1 id="conclusions" id="conclusions">Conclusions</h1>

<p>That is it for the PoC. Just a simple application that hopefully showcases the Go language. It is quirky at times but you get used to it and also there exist enough good libraries out there that you can use to make web application dev possible. I do think it is best used for the things it is being used for right now, which is to make CLI tools that will run everywhere. Like Docker and Kubernetes as well as a webserver called Caddy that can run anywhere.</p>

<p>The thing that I dislike the most is the error handling, or lack thereof. It feels very janky that you have to manually check and bubble errors all over the place. Almost every method returns the error again. This means it is quite cumbersome and you keep writing the same code over and over again.</p>

<p>Also the structure of the Go application is a bit arbitrary, so you can go all out like I did here or just put it all together and keep things as private as possible everywhere. I think this is just all preference and you should make good agreements within the team on what will be the way forward.</p>

<p><a href="https://stealthycoder.writeas.com/tag:code" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">code</span></a> <a href="https://stealthycoder.writeas.com/tag:golang" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">golang</span></a></p>
]]></content:encoded>
      <guid>https://stealthycoder.writeas.com/golang-is-quirky</guid>
      <pubDate>Mon, 31 Aug 2020 07:30:01 +0000</pubDate>
    </item>
    <item>
      <title>Twisted firestarter</title>
      <link>https://stealthycoder.writeas.com/twisted-firestarter?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[I was going down an avenue of seeing if we could implement a better and easier caching for Docker registry utilizing Google Firestore. !--more--&#xA;&#xA;Getting an ember&#xA;&#xA;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 vndr which I am not familiar with since I am not an old school Golang developer. &#xA;&#xA;After making sure the vendor.conf and vndr could play nicely and getting sucked down the rabbit hole of GO111MODULE 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. &#xA;&#xA;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. &#xA;&#xA;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.&#xA;&#xA;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. &#xA;&#xA;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.&#xA;&#xA;Fanning the ember&#xA;&#xA;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). &#xA;&#xA;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 go.mod and probably also in vendor.conf but yeah. My hair already looked liked the Prodigy at this point so I might as well stay committed. &#xA;&#xA;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.&#xA;&#xA;Fire, fire&#xA;&#xA;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. &#xA;&#xA;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. &#xA;&#xA;#100DaysToOffload #docker #golang]]&gt;</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" 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">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" 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" 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"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="https://stealthycoder.writeas.com/tag:docker" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">docker</span></a> <a href="https://stealthycoder.writeas.com/tag:golang" class="hashtag" rel="nofollow"><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>But can I write to it?</title>
      <link>https://stealthycoder.writeas.com/but-can-i-write-to-it?pk_campaign=rss-feed</link>
      <description>&lt;![CDATA[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? !--more--&#xA;&#xA;Stat has that information&#xA;&#xA;So my first inclination was that the os.Stat call has that information. It sort of does, in a way, but only for Linux. There is a Sys() method on the fs.FileInfo which returns a specific struct on Linux. &#xA;&#xA;package main&#xA;&#xA;import (&#xA;&#x9;&#34;fmt&#34;&#xA;&#x9;&#34;os&#34;&#xA;&#x9;&#34;syscall&#34;&#xA;)&#xA;&#xA;func main() {&#xA;&#x9;info, err := os.Stat(&#34;/tmp/some.file&#34;)&#xA;&#x9;if err != nil {&#xA;&#x9;&#x9;fmt.Printf(&#34;%s&#34;, err)&#xA;&#x9;}&#xA;&#x9;if data, ok := info.Sys().(*syscall.Statt); ok {&#xA;&#x9;&#x9;fmt.Printf(&#34;UID: %d\n&#34;, data.Uid)&#xA;&#x9;}&#xA;}&#xA;Is an example of how you get to that part and if you call syscall.Getuid() 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. &#xA;&#xA;Permission bit logic&#xA;&#xA;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. &#xA;&#xA;Sidetrack to Java&#xA;&#xA;So in Java there has been this thing) 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?!?!?&#xA;&#xA;Solution&#xA;&#xA;So I did finally create a solution that was tailored for Unix and Windows separately. &#xA;&#xA;Windows&#xA;&#xA;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:&#xA;&#xA;package main&#xA;&#xA;import (&#xA;&#x9;&#34;fmt&#34;&#xA;&#x9;&#34;syscall&#34;&#xA;)&#xA;&#xA;// https://learn.microsoft.com/en-us/windows/win32/fileio/file-access-rights-constants&#xA;const FILEAPPENDFILE = 0x00000002&#xA;&#xA;// https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilew#parameters at dwShareMode&#xA;const FILELOCK = 0x00000000&#xA;&#xA;func main() {&#xA;&#x9;// Checks if directory is writable&#xA;&#x9;if hwnd, err := syscall.CreateFile(syscall.StringToUTF16Ptr(&#34;C:\\Windows\\system32&#34;), FILEAPPENDFILE, FILELOCK, nil, syscall.OPENEXISTING, syscall.FILEFLAGBACKUPSEMANTICS|syscall.FILEFLAGOPENREPARSEPOINT, 0); err == nil {&#xA;&#x9;&#x9;if err = syscall.CloseHandle(hwnd); err != nil {&#xA;&#x9;&#x9;&#x9;fmt.Printf(&#34;%s\n&#34;, err)&#xA;&#x9;&#x9;}&#xA;&#x9;&#x9;fmt.Printf(&#34;This directory is writable&#34;)&#xA;&#x9;}&#xA;}&#xA;So yeah, a syscall to CreateFile 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 CreateDirectoryW is also an actual call in the Win32 API, which is the only one that can actually create a directory. This is so confusing. &#xA;&#xA;Linux / MacOSX&#xA;&#xA;The other solution was sort of similar but much easier. There is a nice syscall to Access. &#xA;&#xA;package main&#xA;&#xA;import (&#xA;&#x9;&#34;fmt&#34;&#xA;&#x9;&#34;syscall&#34;&#xA;)&#xA;&#xA;func main() {&#xA;&#x9;// Checks if directory is writable&#xA;&#x9;if err := syscall.Access(&#34;/opt/&#34;, syscall.ORDWR); err == nil {&#xA;&#x9;&#x9;fmt.Printf(&#34;This directory is writable&#34;)&#xA;&#x9;}&#xA;}&#xA;&#xA;Conclusion&#xA;&#xA;I feel like all of this code can be hidden away in the Golang standard library and give us a nice os.IsWritable(path string) bool function signature for it. &#xA;&#xA;#100DaysToOffload #devlife #golang]]&gt;</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" 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" 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" 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">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" id="solution">Solution</h2>

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

<h3 id="windows" 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" 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" 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"><span>#</span><span class="p-category">100DaysToOffload</span></a> <a href="https://stealthycoder.writeas.com/tag:devlife" class="hashtag" rel="nofollow"><span>#</span><span class="p-category">devlife</span></a> <a href="https://stealthycoder.writeas.com/tag:golang" class="hashtag" rel="nofollow"><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>
  </channel>
</rss>