{"id":9371,"date":"2019-05-24T09:24:33","date_gmt":"2019-05-24T09:24:33","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=9371"},"modified":"2025-03-10T10:51:47","modified_gmt":"2025-03-10T10:51:47","slug":"how-to-code-efficiently-in-golang","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/how-to-code-efficiently-in-golang","title":{"rendered":"How to Code Efficiently in Golang?"},"content":{"rendered":"<style>\nul.index-list {\n    text-align: left;\n    list-style-type: square;\n}\np{\n   width:100%;\n}\n.post-content p img {\n    margin-bottom: 0 !important;\n}\n.text-orange,.text-orange> strong{\ncolor: #ec6100 !important;\nfont-weight: 700;\n}\n.border-box{\npadding: 12px;\nborder: 1px solid #000;\nmargin-bottom: 16px;\n}\n.border-div{border: 1px solid #000; padding: 22px; text-align: center; margin-bottom: 32px;}\n\t\t.border-bottom{\n\t\t\tborder-bottom: 1px solid #000;\n\t\t\ttext-align: center;\n\t\t\tdisplay: inline-block;\n\t\t}\n\t\t.border-div p{text-align: left;}\n\t\t.cust-list{padding: 0; text-align: left;}\n\t\t.cust-list li{padding-left: 32px; list-style: none}\npre {\n    background: #f7e9dd;\n    border: none;\n    font-size: 16px;\n}\n.cross-platform{\n    background: #f7e9dd;\n    border: none;\n    font-size: 20px;\n    text-align:center;\n    padding:40px;\n}\n.cross-platform a{\n   font-size: 20px !important;\n    font-weight: bold !important;\n    margin-top: 10px;\n    border-radius: 10px !important;\n    background: #ec6100 !important;\n    border: 1px solid transparent !important;\n}\n.final{\n    background: #f7e9dd;\n    border: none;\n    font-size: 20px;\n    text-align:left;\n    padding:40px;\n}\n.final a{\n   font-size: 20px !important;\n    font-weight: bold !important;\n    margin-top: 10px;\n    border-radius: 10px !important;\n    border: 1px solid transparent !important;\n}\n<\/style>\n<p style=\"color:#FFA500\"><strong><em>Quick Summary:<\/em><\/strong><\/p>\n<p><em>Enough of assumptions about the strict Golang programming language. Cutting the rumors out and hearing it straight from an experienced developer, how and what it feels working with Golang.<\/em><\/p>\n<p><em>This blog is a kick-starter for those who want to learn and start working with Golang. Do share your feedback on this blog in the comments below. Also share it with your friends if you find it useful.<\/em><\/p>\n<div class=\"border-div\">\n<h2 class=\"border-bottom\">Table Of Content<\/h2>\n<p><a href=\"#1\">1. The Domination of Golang<\/a><\/p>\n<p><a href=\"#2\">2. Why Golang?<\/a><\/p>\n<p><a href=\"#3\">3. How to code in Packages?<\/a><\/p>\n<p><a href=\"#4\">4. Beware For The Middleware<\/a><\/p>\n<p><a href=\"#5\">5. Custom http.Client turned interceptor<\/a><\/p>\n<p><a href=\"#6\">6. Conclusion <\/a><\/p>\n<p><a href=\"#7\">7. FAQs<\/a><\/p>\n<\/div>\n<h2 id=\"1\">The Domination of Golang<\/h2>\n<p>The very first thing that you need to know about Golang is that it is a very dominating language. If you want to write an optimum Golang code, you need to inherit the coding standard set by it. Golang is just like the terrifying aunt in the neighborhood who\u2019d scream at you if your ball goes in her yard. Add one extra unused variable, and the code won\u2019t run at all, start the variable name with a small case letter, and you won\u2019t be able to use it anywhere. Declare a function inside a package starting with a small case, and you won\u2019t be able to use it anywhere else. Golang is pretty serious about its linting and documentation. If you strictly follow the rules and get along with them, Golang is ergonomic and intuitive. And that helps when you code in other languages too. Your coding standards(even for other technologies) start improving after you do one project in Go.<\/p>\n<p>Coding in Golang is not just about getting the work done or expressing your thoughts or what you have like an idea of a mere algorithm. If you take up a code snippet from C or C++ or Java and translate it to go, it has very little chance of being optimum. To be truly able to get the best out of Golang, you need to understand the gifts that the language has to offer.<\/p>\n<h2 id=\"2\">Why Golang?<\/h2>\n<p>The main reason behind Google to develop Go is to overcome the main two problems it faces. First, COMPILE TIME: Google builds up software that is so gigantic that it takes hours and hours to complete the build. To build up Chrome from scratch, it takes up to 5 hours even on a big fat i7 system. Second up, STRING PROCESSING: Google spends a lot of time reading and analyzing web pages. Which are Strings? Lots and Lots of Strings. Thus, it helps to be efficient. Therefore, in Go, they have mainly focused on a quick compilation and fast string processing. Google has built up a profound library for string manipulations. Even the Garbage Collection in Go makes strings efficient and straightforward to think about unlike some other string libraries (C++). As Golang is statically typed and with the help of efficient linting, go compiles too quickly without the need for dependency checking, thus reducing the expense incurred in creating the build.<\/p>\n<p class=\"boxed bg--secondary\" style=\"border: 1px solid #c7c7c7; box-shadow: 0 0 40px rgba(0, 0, 0, 0.2);\"><strong>Also Read: <\/strong><br \/>\n<a href=\"https:\/\/www.bacancytechnology.com\/blog\/why-use-golang\" target=\"_blank\" rel=\"noopener\">Go Benefits &#038; Use-Cases<\/a><\/p>\n<h2 id=\"3\">How to code in Packages?<\/h2>\n<p>The approach that I mainly follow in creating golang packages is to set it up in the abundance of different small packages. That is isolated and encapsulated within themselves. So what should an efficient package in golang contain? According to me, a package in Go should include the following:<\/p>\n<p>1. Data Types are relevant to the package. This will consist of the structs used in the package. I also prefer creating mutex locks on particular local resources.<\/p>\n<pre>\r\ntype Data struct {\r\n\tSize float64\r\n\tName string\r\n\r\n\tmu sync.Mutex\r\n\tcache map[string]string\r\n}\r\n\r\n- The `mu sync.Mutex protects the Cache used below it.\r\n<\/pre>\n<p>2. The use of interfaces for behavior definition, functions, or methods for logical execution on the structs created.<\/p>\n<p>3. The functions that are the main CRUX of the package. The ones that contain the main logic.<\/p>\n<p>4. And for the last but not least. Differentiate between the functions or structs that need to be private and the ones that need to be public.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_r2-Fn73d2AMKKFIswoweCg.png\" alt=\"Golang Coding\" width=\"624\" height=\"966\" class=\"aligncenter size-full wp-image-9372\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_r2-Fn73d2AMKKFIswoweCg.png 624w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_r2-Fn73d2AMKKFIswoweCg-194x300.png 194w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_r2-Fn73d2AMKKFIswoweCg-13x20.png 13w\" sizes=\"auto, (max-width: 624px) 100vw, 624px\" \/><\/p>\n<p>The practice that I think is the most suitable is to have a file in each package named `init.go.` In this file, there would be the basic and necessary setup for the package. Default Values, refresh tokens, launching different goroutines, etc.<\/p>\n<p>Let\u2019s have a look at the project structure I am working with. The main.go file (not shown in image) is the entry point for any go program. It starts the execution and will import the server from the service package.<\/p>\n<p>As it is visible, each different aspect is bifurcated into a different package.<\/p>\n<p>The \u200arethink package is for reading, connecting or writing into the rethink database.<\/p>\n<p>The auth package is for performing the authentication and the jwt token based logic.<\/p>\n<p>The config package is for manipulating or reading the configurable files.<\/p>\n<p>Now as all the packages cover different aspects, we can write unit tests for each independently. You see the service_test.go file placed in the service package. Similar to it you can have a separate test file for each package. <\/p>\n<h2 id=\"4\">Beware For The Middleware<\/h2>\n<p>Implementing Middleware is one of the most important and useful points. A lot of issues that come with serving content can be handled using simple middleware. Else you\u2019ll require repetitive and annoying code at way too many places. May it be authentication or header checks or even if it is gzip-ing your response. These features are typical for all web services, which can create a lot of pandemonium if you don\u2019t plan them well.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA.png\" alt=\"golang\" width=\"1600\" height=\"615\" class=\"aligncenter size-full wp-image-9374\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA.png 1600w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA-300x115.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA-768x295.png 768w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA-1024x394.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/1_E5XBRQkGeFZlRKrh2Y9HfA-20x8.png 20w\" sizes=\"auto, (max-width: 1600px) 100vw, 1600px\" \/><\/p>\n<p>The idea for it is as simple as it can get. All we need to do is create a function that accepts the handler function. Wraps it up with the custom authentication and returns a request handler at the end. The pseudo-code for it is as below:<\/p>\n<pre>\r\nfunc MyHandler(h *http.Handler) *http.Handler {\r\n    return http.handlerFunc(func(w http.ResponseWriter, r *http.Request){\r\n        fmt.Println(\u201cDoing job before calling the actual handler\u201d)\r\n        h.ServeHttp(w, r)\r\n        fmt.Println(\u201cDoing job after calling the actual handler\u201d)\r\n    })\r\n} \r\n<\/pre>\n<p>As all the extra logic of the handlers are coded differently, what we can do is, we can modify our requests or the response object for all the basic stuff as per our heart\u2019s desire. And the controller logic is left with just the implementation logic.<\/p>\n<p>This comes in handy when all you need is to do a few alterations in every request and response object the Apis process and server. Now I would advise to write up by yourself. The modifications become super easy. But if you don\u2019t want to do so. There are plenty of custom packages available that you can download.<\/p>\n<p class=\"cross-platform\"><strong>Made up your mind for Golang programming language for your upcoming project?<br \/>\n<\/strong><br \/>\nOur salient Go developers will materialize your idea.<br \/>\n <a href=\"https:\/\/www.bacancytechnology.com\/hire-golang-developer\" target=\"_blank\" class=\"btn btn--sm btn--primary\" rel=\"noopener\"><strong>Hire Golang Developers Now!<\/strong><\/a><\/p>\n<h2 id=\"5\">Custom http.Client turned interceptor<\/h2>\n<p>It is really frequent in our backend that we need to make API calls to different services for data. We might scrape some data of a custom website or hit up google for location details. But the requirement to make network calls will arise. So the easiest solution that comes to mind is to use HTTP.Post(\u2026) Method predefined in Go\u2019s HTTP package. BUT PLEASE DON\u2019T!<\/p>\n<p>Instead of using the default HTTP Client object to make the network calls, what we can do is to write up a separate function that defines a custom client object. And the first thing that you should do is to SET A NETWORK TIMEOUT. The default HTTP. The client DOES NOT have a timeout. So the amount of time required if the Third-Party API is down will increase the response time way too much.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code.png\" alt=\"code golang\" width=\"1600\" height=\"432\" class=\"aligncenter size-full wp-image-9376\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code.png 1600w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code-300x81.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code-768x207.png 768w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code-1024x276.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2019\/05\/code-20x5.png 20w\" sizes=\"auto, (max-width: 1600px) 100vw, 1600px\" \/><\/p>\n<p>Image <a href=\"https:\/\/blog.cloudflare.com\/the-complete-guide-to-golang-net-http-timeouts\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/p>\n<p>So how do we convert this HTTP.Client to an interceptor? Or what will be the use of it? Well if the interceptor is well coded, then that function will be the singular pipe, that every network call will have to pass through. If so, you can apply authentication, redirections, modifications of res\/req, and many more things. This function will be the junction, where you can do all so awesome stuff aside from just making the network calls. Whatever you want, you name it; you got it! Statistics, analytics, customization, redirection logic. Your creativity enforces the limits. Here is a code that I use myself:<\/p>\n<pre>\r\n\/\/ Fetch makes network calls using the method (POST\/GET..), the URL \/\/ to hit, headers to add (if any), and the body of the request.\r\n\/\/ Feel free to add more stuff to before\/after making the actual n\/w call!\r\nfunc Fetch(method string, url string, header map[string]string, body io.Reader) (*http.Response, err) {\r\n  \/\/ Create client with required custom parameters.\r\n  \/\/ Options: Disable keep-alives, 30sec n\/w call timeout.\r\n  client := &http.Client{\r\n      Transport: &http.Transport{\r\n          DisableKeepAlives: true,\r\n      },\r\n      Timeout: time.Duration(10 * time.Second),\r\n  }\r\n  \/\/ Create request.\r\n  req, _ := http.NewRequest(method, url, body)\r\n  \/\/ Add any required headers.\r\n  for key, value := range header {\r\n      req.Header.Add(key, value)\r\n  } \r\n  \/\/ Perform said network call.\r\n  res, err := client.Do(req)\r\n      if err != nil {\r\n      glog.Error(err.Error())   \/\/ use glog it's amazing\r\n      return nil, err\r\n  }\r\n  \/\/ If response from network call is not 200, return error too.\r\n  if res.StatusCode != http.StatusOK {\r\n      return res, errors.New(\"Network call did not return SUCCESS!\")\r\n  }\r\n  return res, nil\r\n}\r\n<\/pre>\n<h2 id=\"6\">Conclusion<\/h2>\n<p>All this code will do is use your written HTTP. Client to make the network call for you. You can use and modify the code given above to measure response time, log metrics of error cases, modify cookies, etc. In case if you don\u2019t know how to get it done, then hire Golang developer from us and leverage our top-of-the-line <a href=\"https:\/\/www.bacancytechnology.com\/golang-development\" rel=\"noopener\" target=\"_blank\">Golang development services<\/a>  Go ahead, have fun!<\/p>\n<p>From one Gopher to all of you out there, keep building amazing stuff, stay awesome!<\/p>\n<style>\n.faqs-tran-black-border li{ list-style:none;}\n<\/style>\n<section class=\"bg--white faqs-tran-black-border\" style=\"padding-top: 60px;\">\n<div class=\"container\">\n<div class=\"row\">\n<div class=\"col-sm-12\">\n<h2 id=\"7\">FAQs<\/h2>\n<ul class=\"accordion accordion--oneopen\">\n<li>\n<div class=\"accordion__title\"> <span class=\"h5\">What are some of the unmatched features of Go language?<\/span> <\/div>\n<div class=\"accordion__content\">\n<p>No Generics, Single Executables, and no dynamic Libraries are the three unmatched features of Golang.\n<\/p>\n<\/p><\/div>\n<\/li>\n<li>\n<div class=\"accordion__title\"> <span class=\"h5\">Which solutions does Go provide?<\/span> <\/div>\n<div class=\"accordion__content\">\n<p>Some of the amazing results that Golang offers:<br \/>\n\u29bf Speedy compilation and execution<br \/>\n\u29bf Reliable code &#038; documentation<br \/>\n\u29bf Language consistency<br \/>\n\u29bf Program versioning facilitation<br \/>\n\u29bf Development with multiple languages<br \/>\n\u29bf Dependency maintenance\n<\/p>\n<\/p><\/div>\n<\/li>\n<li>\n<div class=\"accordion__title\"> <span class=\"h5\">Can we say that Go is OOP language?<\/span> <\/div>\n<div class=\"accordion__content\">\n<p>The answer is both- yes and no. Golang is an object-oriented language, but still, it doesn\u2019t follow any hierarchy.\/p>\n              <\/p><\/div>\n<\/li>\n<li>\n<div class=\"accordion__title\"> <span class=\"h5\">Can I use Golang as a scripting language?<\/span> <\/div>\n<div class=\"accordion__content\">\n<p>Yes, you can use Golang in place of scripting languages such as javascript.\n<\/p>\n<\/p><\/div>\n<\/li>\n<li>\n<div class=\"accordion__title\"> <span class=\"h5\">What are the drawbacks of using Golang?<\/span> <\/div>\n<div class=\"accordion__content\">\n<p>Go\u2019s interface methods do not support default implementations, Go lacks generics, it is quite a naive and young programming language, and there is no reusability opinion with Go.\n<\/p>\n<\/p><\/div>\n<\/li>\n<\/ul><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/section>\n","protected":false},"excerpt":{"rendered":"<p>Quick Summary: Enough of assumptions about the strict Golang programming language. Cutting the rumors out and hearing it straight from an experienced developer, how and what it feels working with Golang. This blog is a kick-starter for those who want to learn and start working with Golang. Do share your feedback on this blog in [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":9378,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[1152],"tags":[],"coauthors":[1585],"class_list":["post-9371","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-golang"],"acf":[],"modified_by":"Binal Prajapati","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/9371","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=9371"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/9371\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/9378"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=9371"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=9371"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=9371"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=9371"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}