<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>Forem: Dawn Zhao</title>
    <description>The latest articles on Forem by Dawn Zhao (@dawnzhao).</description>
    <link>https://forem.com/dawnzhao</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1623329%2Fd666b566-4e52-4fd7-be8c-205b56d642ed.png</url>
      <title>Forem: Dawn Zhao</title>
      <link>https://forem.com/dawnzhao</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/dawnzhao"/>
    <language>en</language>
    <item>
      <title>Golang Security Review Guide</title>
      <dc:creator>Dawn Zhao</dc:creator>
      <pubDate>Thu, 22 Aug 2024 09:08:25 +0000</pubDate>
      <link>https://forem.com/marscode/golang-security-review-guide-4kk5</link>
      <guid>https://forem.com/marscode/golang-security-review-guide-4kk5</guid>
      <description>&lt;p&gt;Written by Abdullah Al-Sultani&lt;br&gt;
Linkedin:&lt;a href="https://uk.linkedin.com/in/abdullahhussam" rel="noopener noreferrer"&gt;Abdullah Al-Sultani&lt;/a&gt;&lt;br&gt;
Mailbox📮:&lt;a href="mailto:abdullah@alsultani.me"&gt;abdullah@alsultani.me&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Go is a statically typed, compiled high-level programming language designed at Google. It is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency. Most of our apps and backend rely on Golang. Therefore, we found it important to document the review process for such applications. The checklist of this article can be found at the end of the page. &lt;/p&gt;
&lt;h2&gt;
  
  
  First things first
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://gobyexample.com/" rel="noopener noreferrer"&gt;Go by Example&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Go related
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;In golang, the library &lt;code&gt;net/http&lt;/code&gt; usually transforms the path to a canonical one before accessing it:

&lt;ul&gt;
&lt;li&gt;/flag/ -- Is responded with a redirect to /flag&lt;/li&gt;
&lt;li&gt;/../flag --- Is responded with a redirect to /flag&lt;/li&gt;
&lt;li&gt;/flag/. -- Is responded with a redirect to /flag&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;If the &lt;code&gt;CONNECT&lt;/code&gt; method is used, this doesn't happen. So, if you need to access some protected resource, you can abuse this trick:
&lt;code&gt;curl --path-as-is -X CONNECT http://hack.me/../flag&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;go =&amp;lt; 1.15&lt;/code&gt; has an issue with &lt;code&gt;Range&lt;/code&gt; header that can be exploited in some contexts &lt;a href="https://github.com/golang/go/issues/40940" rel="noopener noreferrer"&gt;https://github.com/golang/go/issues/40940&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;When go parses a JSON response, it sets the non-existent fields that are defined as strings as empty strings instead of nil. &lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  What you are looking for
&lt;/h2&gt;
&lt;h3&gt;
  
  
  Vulnerable 3rd-Party Modules
&lt;/h3&gt;

&lt;p&gt;You can use &lt;a href="https://docs.snyk.io/getting-started/quickstart" rel="noopener noreferrer"&gt;https://docs.snyk.io/getting-started/quickstart&lt;/a&gt; &lt;br&gt;
Simply running &lt;code&gt;snyk test&lt;/code&gt; on a Go application will parse your modules and report back any known &lt;a href="https://learn.snyk.io/lesson/cve/" rel="noopener noreferrer"&gt;CVEs&lt;/a&gt;, as well as info about any fixed versions of them that you can upgrade to. &lt;/p&gt;
&lt;h3&gt;
  
  
  RCE - Remote Code Execution
&lt;/h3&gt;

&lt;p&gt;Command injection occurs when the user input gets executed on the server as system command. For instance, look at the following code:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;binary, lookErr := exec.LookPath("sh")
  if lookErr != nil {
      panic(lookErr)
}
env := os.Environ()
args := []string{"sh", "-c", req.FormValue("name")}
execErr := syscall.Exec(binary, args, env)
if execErr != nil {
    panic(execErr)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Most of the time, the application gets user input through forms. The code above receives the &lt;code&gt;name&lt;/code&gt; value from a form and passes it to the dangerous function &lt;code&gt;syscall.Exec&lt;/code&gt; which will execute the command on the server. However, when the developer expects a name, the attacker can submit something like &lt;br&gt;
&lt;code&gt;John &amp;amp; whoami &amp;gt; /var/www/static/whoami.txt&lt;/code&gt;&lt;br&gt;
This command will store the output of &lt;code&gt;whoami&lt;/code&gt; in whoami.txt in the static folder. Golang offers many to execute commands to list a few of them: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;exec.Command()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exec.CommandContext()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;syscall.Exec()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;os.StartProcess()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exec.Cmd()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Getting any user controlled input inside these functions directly without validating is extremely dangerous. Make sure to filter the input or use allow-list the commands that want to be executed like the following: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;type OSProgram uint64

const (
    LS OSProgram = iota
    Cat
    Echo
    Grep
)

func CallOSCommand(program OSProgram, args ...string) {
    switch program {
    case LS:
        exec.Command("ls", args...)
    case Cat:
        exec.Command("cat", args...)
    case Echo:
        exec.Command("echo", args...)
    case Grep:
        exec.Command("grep", args...)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  SQL Injection
&lt;/h3&gt;

&lt;p&gt;Sql injection occurs when user input is being inserted into the sql query without filtering or sanitizing. The root cause of this issue is old practice, which is &lt;strong&gt;string concatenation&lt;/strong&gt;. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ctx := context.Background() 
customerId := r.URL.Query().Get("id") 
query := "SELECT number, cvv FROM creditcards WHERE customerId = " + customerId 
row, _ := db.QueryContext(ctx, query)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;As you can notice, the &lt;code&gt;customerId&lt;/code&gt; is &lt;strong&gt;user-supplied&lt;/strong&gt; input. And it is being added to the query without any filteration. What if an attacker submits &lt;code&gt;customerId&lt;/code&gt; as &lt;code&gt;1 or 1=1&lt;/code&gt;? &lt;br&gt;
The sql query will become: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;SELECT number, cvv FROM creditcards WHERE customerId = 1 or 1=1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;This will dump the full table records since &lt;code&gt;1 or 1=1&lt;/code&gt; is always true. The solution for this issue is called &lt;a href="https://pkg.go.dev/database/sql#DB.Prepare" rel="noopener noreferrer"&gt;Prepared Statments&lt;/a&gt;. The safe code will look like this: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;ctx := context.Background() 
customerId := r.URL.Query().Get("id") 
query := "SELECT number, expireDate, cvv FROM creditcards WHERE customerId = ?" 
stmt, _ := db.QueryContext(ctx, query, customerId)  
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Notice the placeholder &lt;code&gt;?&lt;/code&gt; . Your query is now:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Readable &lt;/li&gt;
&lt;li&gt;Safe &lt;/li&gt;
&lt;li&gt;And short &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The placeholder syntax is database-specific. You may see the following syntaxes depending on the project requirements: &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;MySQL&lt;/strong&gt;&lt;br&gt;
WHERE col = ? &lt;br&gt;
VALUES(?, ?, ?)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;PostgreSQL&lt;/strong&gt;&lt;br&gt;
WHERE col = $1&lt;br&gt;
VALUES($1, $2, $3)&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Oracle&lt;/strong&gt; &lt;br&gt;
WHERE col = :col&lt;br&gt;
VALUES(:val1, :val2, :val3)&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;❗️GORM can cause SQL injection even if the prepare statement is being used. If you pass string parameters to numerical IDs, for example,&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;userInput := "jinzhu;drop table users;"

// safe, will be escaped
db.Where("name = ?", userInput).First(&amp;amp;user)

// SQL injection
db.Where(fmt.Sprintf("name = %v", userInput)).First(&amp;amp;user)

// will be escaped
db.First(&amp;amp;user, "name = ?", userInput)

// SQL injection
db.First(&amp;amp;user, fmt.Sprintf("name = %v", userInput))

userInputID := "1=1;drop table users;"
// safe, return error
id,err := strconv.Atoi(userInputID)
if err != nil {
    return error
}
db.First(&amp;amp;user, id)

// SQL injection
db.First(&amp;amp;user, userInputID)
// SELECT * FROM users WHERE 1=1;drop table users;

// SQL injection
db.Select("name; drop table users;").First(&amp;amp;user)
db.Distinct("name; drop table users;").First(&amp;amp;user)
db.Model(&amp;amp;user).Pluck("name; drop table users;", &amp;amp;names)
db.Group("name; drop table users;").First(&amp;amp;user)
db.Group("name").Having("1 = 1;drop table users;").First(&amp;amp;user)
db.Raw("select name from users; drop table users;").First(&amp;amp;user)
db.Exec("select name from users; drop table users;")
db.Order("name; drop table users;").First(&amp;amp;user)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;strong&gt;String concatenation functions and methods&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;💡Always take a deep look when reviewing string concatenation process inside a function. Most of the time, developer forgets about possible security issues. Whenever you see non-standard SQL query generator there is a possibility of SQL injection. &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Function/Method&lt;/strong&gt; &amp;amp; &lt;em&gt;Example&lt;/em&gt;：&lt;br&gt;
&lt;strong&gt;Plus operator&lt;/strong&gt;：&lt;br&gt;
&lt;em&gt;name := "A" + " " + "b" // A b&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;String append:&lt;/strong&gt; &lt;br&gt;
&lt;em&gt;u := "This"&lt;br&gt;
v := " is working."&lt;br&gt;
u += v   // sets u to "This is working."&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Join() function:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;s := []string{"This", "is", "a", "string."} &lt;br&gt;
v := strings.Join(s, " ") &lt;br&gt;
fmt.Println(v)  // This is a string.&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Sprintf() method:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;s1 := "abc" &lt;br&gt;
s2 := "xyz" &lt;br&gt;
v := fmt.Sprintf("%s%s", s1, s2) &lt;br&gt;
fmt.Println(v) // abcxyz&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Bytes buffer method:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;var b bytes.Buffer &lt;br&gt;
b.WriteString("abc") &lt;br&gt;
b.WriteString("def") // append &lt;br&gt;
fmt.Println(b.String()) // abcdef&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Strings builder method:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;var sb strings.Builder &lt;br&gt;
sb.WriteString("First") &lt;br&gt;
sb.WriteString("Second") &lt;br&gt;
fmt.Println(sb.String())    // FirstSecond&lt;/em&gt;&lt;br&gt;
&lt;strong&gt;Repeat() Method:&lt;/strong&gt;&lt;br&gt;
&lt;em&gt;fmt.Println(strings.Repeat("abc", 3))  // abcabcabc&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Real life case&lt;/strong&gt;&lt;br&gt;
Our colleague Anton found an interesting SQL injection vulnerability in the well known SQL library. As we stated before, the root cause of the issue was insecure &lt;strong&gt;string concatenation&lt;/strong&gt;. &lt;br&gt;
The vulnerable code was in &lt;code&gt;gen_sql.go&lt;/code&gt; which is used to generate the SQL query, the vulnerable snippet:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;switch c.value.(type) {
        case []interface{}:
                s := []string{}
                tempInter := c.value.([]interface{})
                if len(c.value.([]interface{})) == 0 {
                        return ""
                }
                if len(tempInter) == 0 {
                        return ""
                }
                if len(tempInter) &amp;gt; LIST_LIMIT {
                        tempInter = tempInter[:LIST_LIMIT]
                }
                for _, i := range tempInter {
                        vv := fmt.Sprintf("%v", i)
                        switch i.(type) {
                        case string:
                                vv = fmt.Sprintf("'%v'", i)
                        }
                        s = append(s, vv)
                }
                v = QuoteJoinString(s, "%v", ",")
        case []string:
                v = fmt.Sprintf("'%v'", c.value)

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The code does the following: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It checks the data type of &lt;code&gt;c&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Then, if it is an array of &lt;code&gt;interface&lt;/code&gt; it appends the data (the string) to the query without escaping it. &lt;/li&gt;
&lt;li&gt;Similarly, for &lt;code&gt;string&lt;/code&gt; data type.&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "fmt"

    "code.byted.org/dp/clickhouse_client_golang"
)

func main() {

        userData := "test' or title = 'test" // user-controlled input 

    sql := clickhouse_client_golang.NewSqlGenerator().
        AddSelect("title").
        From("table").
        AddWhereCond(clickhouse_client_golang.NewCond("title = ?", []interface{}{userData})).
        AddWhereCond(clickhouse_client_golang.NewCond("title = ?", userData)).
        Sql()

    fmt.Println(sql)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Basically, it will escape the &lt;code&gt;AddWhereCond&lt;/code&gt; function prepare statement. It will generate the following query: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;select title from table where (title = 'test' or title = 'test') and (title = 'test' or title = 'test')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  XSS - Cross Site Scripting
&lt;/h3&gt;

&lt;p&gt;Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites. XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser-side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.&lt;br&gt;
There are three types of XSS: &lt;br&gt;
&lt;strong&gt;Reflected XSS Attacks&lt;/strong&gt;&lt;br&gt;
Reflected attacks are those where the injected script is reflected off the web server, such as in an error message, search result, or any other response that includes some or all of the input sent to the server as part of the request. Reflected attacks are delivered to victims via another route, such as in an e-mail message, or on some other website. When a user is tricked into clicking on a malicious link, submitting a specially crafted form, or even just browsing to a malicious site, the injected code travels to the vulnerable web site, which reflects the attack back to the user’s browser. The browser then executes the code because it came from a “trusted” server. Reflected XSS is also sometimes referred to as Non-Persistent or Type-I XSS (the attack is carried out through a single request / response cycle).&lt;br&gt;
&lt;strong&gt;Stored XSS Attacks&lt;/strong&gt;&lt;br&gt;
Stored attacks are those where the injected script is permanently stored on the target servers, such as in a database, in a message forum, visitor log, comment field, etc. The victim then retrieves the malicious script from the server when it requests the stored information. Stored XSS is also sometimes referred to as Persistent or Type-II XSS.&lt;br&gt;
&lt;strong&gt;DOM XSS Attacks&lt;/strong&gt;&lt;br&gt;
DOM Based XSS (or as it is called in some texts, “type-0 XSS”) is an XSS attack wherein the attack payload is executed as a result of modifying the DOM “environment” in the victim’s browser used by the original client side script, so that the client side code runs in an “unexpected” manner. That is, the page itself (the HTTP response that is) does not change, but the client side code contained in the page executes differently due to the malicious modifications that have occurred in the DOM environment. This is in contrast to other XSS attacks (stored or reflected), wherein the attack payload is placed in the response page (due to a server side flaw).&lt;br&gt;
The following code is vulnerable to Reflected XSS:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main 
import "net/http" 
import "io" 
func handler (w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, r.URL.Query().Get("param1")) 
} 
func main () {
    http.HandleFunc("/", handler) 
    http.ListenAndServe(":8080", nil)
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;As &lt;code&gt;Content-Type&lt;/code&gt; HTTP response header is not explicitly defined, Go &lt;code&gt;http.DetectContentType&lt;/code&gt; default value will be used, which follows &lt;a href="https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-typ" rel="noopener noreferrer"&gt;MIME Sniffing&lt;/a&gt; standard. The &lt;code&gt;io.WriteString&lt;/code&gt; will return the user input &lt;code&gt;param1&lt;/code&gt; as it is without filteration or sanitization. Going to &lt;a href="http://127.0.0.1:8080/?param1=%3Cscript%3Ealert(1)%3C/script%3E" rel="noopener noreferrer"&gt;http://127.0.0.1:8080/?param1=%3Cscript%3Ealert(1)%3C/script%3E&lt;/a&gt; will cause XSS. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8ds7hsp57un3td2knha.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fg8ds7hsp57un3td2knha.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;strong&gt;Dangerous functions:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;template.HTML()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.HTMLAttr()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.CSS()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.JS()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.JSStr()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.Srcset()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.URL()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;fmt.Fprintf()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;io.WriteString()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;writer.Write()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  SSRF - Server Side Request Forgery
&lt;/h3&gt;

&lt;p&gt;If the application makes HTTP requests to URL provided by untrused source (such as user), and no protection is implemented, then it might be vulnerable to SSRF attacks. The attacker can send a request to the internal network or the server's localhost. The outcome can differ from one case to another. For example, an attacker can use the server to send requests to bypass certain firewall rules that mark the vulnerable server as trusted service. &lt;br&gt;
In Go, we can use the &lt;code&gt;net/http&lt;/code&gt; package in order to help us make our own HTTP requests. Here are a few examples: &lt;br&gt;
&lt;code&gt;http.X&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;resp, err := http.Get("http://example.com/")
...
resp, err := http.Post("http://example.com/upload", "image/jpeg", &amp;amp;buf)
...
resp, err := http.PostForm("http://example.com/form",
        url.Values{"key": {"Value"}, "id": {"123"}})

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;For control over HTTP client headers, redirect policy, and other settings, create a &lt;code&gt;Client&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;client := &amp;amp;http.Client{
        CheckRedirect: redirectPolicyFunc,
}

resp, err := client.Get("http://example.com")
// ...

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("If-None-Match", `W/"wyzzy"`)
resp, err := client.Do(req)
// ...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;A vulnerable code snippet, the following code gets user input and passes it to &lt;code&gt;http.Get&lt;/code&gt; directly: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
   "io/ioutil"
   "log"
   "net/http"
)

func main() {
   userControllerd := "http://localhost:8000"
   resp, err := http.Get(userControllerd)
   if err != nil {
      log.Fatalln(err)
   }
   //We Read the response body on the line below.
   body, err := ioutil.ReadAll(resp.Body)
   if err != nil {
      log.Fatalln(err)
   }
   //Convert the body to type string
   sb := string(body)
   log.Printf(sb)
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Fixing SSRF could be tricky. You need to validate the address before connecting to it. However, this must be done at a low layer to be effective to prevent &lt;a href="https://en.wikipedia.org/wiki/DNS_rebinding" rel="noopener noreferrer"&gt;DNS Rebinding&lt;/a&gt; attacks.&lt;/p&gt;
&lt;h3&gt;
  
  
  File Inclusion
&lt;/h3&gt;

&lt;p&gt;The ability to read files on the server by accepting filename or file path from user-controlled input. The following function is vulnerable to this kind of attack. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const ROOT string = "/path/to/root/%s"
func getFileByName(file_name string) string { // fine_name is controlled by user 
   path := fmt.Sprintf(ROOT, file_name)
   buffer, err := ioutil.ReadFile(path)
   if err != nil {
      return name
   }
   return buffer
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Since the &lt;code&gt;file_name&lt;/code&gt; is controlled by user, it is possible to retrieve arbitrary files in the filesystems by the means of &lt;code&gt;../&lt;/code&gt;. For instance, &lt;code&gt;getFileByName("../../../etc/passwd")&lt;/code&gt; can read the passwd file inside the linux machine. This results in the absolute path &lt;code&gt;/path/to/root/../../../etc/passwd&lt;/code&gt;, and its canonicalized form &lt;code&gt;/etc/passwd&lt;/code&gt;. To remediate vulnerability, the &lt;code&gt;path&lt;/code&gt; variable can be safely built as follows:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;path := fmt.Sprintf(ROOT, path.Base(file_name))
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;If the app uses &lt;a href="https://pkg.go.dev/path#Base" rel="noopener noreferrer"&gt;path.Base&lt;/a&gt; or other checks before passing it to the &lt;code&gt;ioutil.ReadFile&lt;/code&gt; it is considered to be secure unless the checks are insufficient or bypassable. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;filepath.Join()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;filepath.Clean()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Demonstrated by several bug reports, &lt;code&gt;filepath.Join()&lt;/code&gt; is a common culprit for directory traversal vulnerabilities. The reason might be that the documentation is a little misleading. &lt;br&gt;
&lt;strong&gt;Real life example&lt;/strong&gt;&lt;br&gt;
A good example of this issue is &lt;a href="https://github.com/grafana/grafana/security/advisories/GHSA-8pjx-jj86-j47p" rel="noopener noreferrer"&gt;CVE-2021-43798&lt;/a&gt;. Let's explore it. &lt;br&gt;
The vulnerable code was &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// /public/plugins/:pluginId/*
func (hs *HTTPServer) getPluginAssets(c *models.ReqContext) {
        pluginID := web.Params(c.Req)[":pluginId"]
        plugin, exists := hs.pluginStore.Plugin(c.Req.Context(), pluginID)
        if !exists {
                c.JsonApiErr(404, "Plugin not found", nil)
                return
        }

        requestedFile := filepath.Clean(web.Params(c.Req)["*"])
        pluginFilePath := filepath.Join(plugin.PluginDir, requestedFile)

        if !plugin.IncludedInSignature(requestedFile) {
                hs.log.Warn("Access to requested plugin file will be forbidden in upcoming Grafana versions as the file "+
                        "is not included in the plugin signature", "file", requestedFile)
        }

        // It's safe to ignore gosec warning G304 since we already clean the requested file path and subsequently
        // use this with a prefix of the plugin's directory, which is set during plugin loading
        // nolint:gosec
        f, err := os.Open(pluginFilePath)
        if err != nil {
                if os.IsNotExist(err) {
                        c.JsonApiErr(404, "Plugin file not found", err)
                        return
                }
                c.JsonApiErr(500, "Could not open plugin file", err)
                return
        }
        defer func() {
                if err := f.Close(); err != nil {
                        hs.log.Error("Failed to close file", "err", err)
                }
        }()
        fi, err := f.Stat()
        if err != nil {
                c.JsonApiErr(500, "Plugin file exists but could not open", err)
                return
        }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;As we can see, the user-controlled value was being passed to &lt;code&gt;filepath.Clean()&lt;/code&gt; function in order to clean it from &lt;code&gt;..&lt;/code&gt;. However, it only does that (remove the traversal) when the value starts with a forward slash (&lt;code&gt;/&lt;/code&gt;). Then, the value got passed to &lt;code&gt;filepath.Join()&lt;/code&gt; which will normalize the path with the predefined &lt;code&gt;plugin.PluginDir&lt;/code&gt; value. The attacker could use &lt;code&gt;../&lt;/code&gt; to traverse the filesystem. &lt;br&gt;
*&lt;em&gt;Exploit: *&lt;/em&gt;&lt;br&gt;
To read &lt;code&gt;/etc/passwd&lt;/code&gt; content, you had to send the following request: &lt;br&gt;
&lt;code&gt;curl --path-as-is&lt;/code&gt; &lt;code&gt;http://localhost:3000/public/plugins/alertlist/../../../../../../../../etc/passwd&lt;/code&gt; &lt;/p&gt;
&lt;h3&gt;
  
  
  XXE - XML External Entity
&lt;/h3&gt;

&lt;p&gt;Go is shipped with native XML parser &lt;code&gt;encoding/xml&lt;/code&gt; that is not vulnerable to XXE. However, parse is used to mere XML parsing and manipulating. It doesn't come with advanced features like validation. Therefore, sometimes developers use third party libraries such as &lt;code&gt;libxml2&lt;/code&gt;. Here is an example,&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// open the form file
file, err := c.FormFile("xml")
xml, err := file.Open()
defer xml.Close()

// parse the XML body
p := parser.New(parser.XMLParseNoEnt)
doc, err := p.ParseReader(xml)
defer doc.Free()

// use the XML document and return data to the user...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;If XXE is enabled in the configuration (parser.XMLParseNoEnt is set in the parser), and the user can control the XML input data. They can send the following XML&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;!DOCTYPE d [&amp;lt;!ENTITY e SYSTEM "file:///etc/passwd"&amp;gt;]&amp;gt;&amp;lt;t&amp;gt;&amp;amp;e;&amp;lt;/t&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;After the file content gets parsed through &lt;code&gt;ParseReader&lt;/code&gt; the response will retrieve the content of &lt;code&gt;/etc/passwd&lt;/code&gt; &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;💡Parsing of external entities is disabled by default. Make sure to check that before jumping to conclusions. &lt;/p&gt;
&lt;/blockquote&gt;
&lt;h3&gt;
  
  
  Authentication
&lt;/h3&gt;
&lt;h4&gt;
  
  
  Password storing
&lt;/h4&gt;

&lt;p&gt;The first rule you need to know is to &lt;strong&gt;never store the plaintext&lt;/strong&gt; of the user's password. For security reasons, you need to use a one-way function to generate a hash for the given password and you can store this hash. The password needs to include salt and/or pepper before storing it, to make sure no two users have the same hash even if they use the same password. Let's take a look at the following code: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
        "context"
        "crypto/rand"
        "crypto/md5"
)

func main() {
        ctx := context.Background()
        email := []byte("john.doe@somedomain.com")
        password := []byte("47;u5:B(95m72;Xq")
        // create random word
        salt := "RandomValue123ABC"
        // let's create MD5(salt+password)
        h := md5.New()
        io.WriteString(h, salt)
        io.WriteString(h, password)
        h := hash.Sum(nil)
        // this is here just for demo purposes
        //
        // fmt.Printf("email : %s\n", string(email))
        // fmt.Printf("password: %s\n", string(password))
        // fmt.Printf("salt : %x\n", salt)
        // fmt.Printf("hash : %x\n", h)
        // you're supposed to have a database connection
        stmt, err := db.PrepareContext(ctx, "INSERT INTO accounts SET hash=?, salt=?, email=?")
        if err != nil {
                panic(err)
        }
        result, err := stmt.ExecContext(ctx, h, salt, email)
        if err != nil {
                panic(err)
        }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The code above has many issues. First, it uses &lt;code&gt;MD5&lt;/code&gt; which is cryptographically broken and should not be used for secure applications. And salt (In cryptography, a salt is random data that is used as an additional input to a one-way function that hashes data, a password or passphrase. Salts are used to safeguard passwords in storage.) is a constant value. The hashing algorithms recommended by OWASP are bcrypt , PDKDF2 , Argon2 and scrypt. These will take care of hashing and salting passwords in a robust way. Any use for in-house built in logic needs a deep look because of the golden rule in crypto: &lt;code&gt;never roll your own crypto!&lt;/code&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  Logic
&lt;/h4&gt;

&lt;p&gt;Many issues occur while validating the user input before authenticating. Let's take a vulnerable example: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func check(u, p string) bool {
  password:= tt.GetUser(u).password
  user:= tt.GetUser(u)
  if u == user || p == password {
    return true 
  }
  return false
} 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The previous code makes an illogical mistake. The OR operator returns &lt;code&gt;true&lt;/code&gt; if one of the cases is &lt;code&gt;true&lt;/code&gt;. Since the user exists in TT database, the following check will return true even if the password is wrong. &lt;br&gt;
Let's take another example: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func auth(fn http.HandlerFunc) http.HandlerFunc {
  return func(w http.ResponseWriter, r *http.Request) {
    user, pass, _ := r.BasicAuth()
    if !check(user, pass) {
       w.Header().Set("WWW-Authenticate", "Basic realm=\\"MY REALM\\"")
       http.Error(w, "Unauthorized.", 401)
       // return needs to be here to fix this issue 
    }
    fn(w, r)
  }
}
func check(u, p){
    [...]
}
func handler(w http.ResponseWriter, r *http.Request) {
    [...]
}

func main() {
    http.HandleFunc("/",auth(handler))
    log.Fatal(http.ListenAndServe(":8080", nil))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;&lt;code&gt;auth&lt;/code&gt; function has no return when the check fails. So, in both cases, it will trigger the callback function &lt;code&gt;handler&lt;/code&gt;. &lt;/p&gt;
&lt;h4&gt;
  
  
  Sessions control
&lt;/h4&gt;

&lt;p&gt;The flow of session process could be seen in the following image &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4r07rakmn6xufoywrf8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz4r07rakmn6xufoywrf8.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
Let's talk about session generating. The function below for example:  &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// create a JWT and put in the clients cookie 
func setToken(res http.ResponseWriter, req *http.Request) {
     ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;You need to make sure that the session identifier is generated randomly, so it stays reliable against brute-forcing.&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 
signedToken, _ := token.SignedString([]byte("secret")) //our secret
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Now that we have a sufficiently strong token, we must also set the &lt;code&gt;Domain&lt;/code&gt;, &lt;code&gt;Path&lt;/code&gt; , &lt;code&gt;Expires&lt;/code&gt; , &lt;code&gt;HTTP only&lt;/code&gt; , &lt;code&gt;Secure&lt;/code&gt; for our cookies. In this case, the &lt;code&gt;Expires&lt;/code&gt; value is, in this example, set to 30 minutes since we are considering our application a low-risk application. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Our cookie parameter
cookie := http.Cookie{
Name: "Auth",
Value: signedToken,
Expires: expireCookie,
HttpOnly: true,
Path: "/",
Domain: "127.0.0.1",
Secure: true
}
http.SetCookie(res, &amp;amp;cookie) //Set the cookie
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Upon sign-in, a new session is always generated. &lt;strong&gt;The old session is never re-used&lt;/strong&gt;, even if it is not expired. This will protect the application from &lt;a href="https://owasp.org/www-community/attacks/Session_fixation#:~:text=Session%20Fixation%20is%20an%20attack,specifically%20the%20vulnerable%20web%20application." rel="noopener noreferrer"&gt;Session Fixation&lt;/a&gt;. Furthermore, session identifiers should never be exposed in URL's. They should only be located in the HTTP cookie header. &lt;/p&gt;
&lt;h3&gt;
  
  
  Access Control
&lt;/h3&gt;

&lt;p&gt;When a user tries to access authorization decisions, it must be checked if they are authorized to perform these actions. Access control highly relies on business logic. In case of a failure, access control should fail securely. In Go we can use &lt;code&gt;defer&lt;/code&gt; to achieve this. Important operations where access controls must be enforced in order to prevent an unauthorized user from accessing them are as follows: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;File and other resources &lt;/li&gt;
&lt;li&gt;Protected URL's &lt;/li&gt;
&lt;li&gt;Protected functions &lt;/li&gt;
&lt;li&gt;Direct object references &lt;/li&gt;
&lt;li&gt;Services &lt;/li&gt;
&lt;li&gt;Application data &lt;/li&gt;
&lt;li&gt;User and data attributes and policy information.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If any action is being taken, you must check the user capabilities before executing the action. For example, &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    // Init the mux router
    router: = mux.NewRouter()
    // Route handles &amp;amp; endpoints
    // Get all books
        router.HandleFunc("/books/", GetBooks).Methods("GET")
    // Create a book
        router.HandleFunc("/books/", CreateBook).Methods("POST")
    // Delete a specific book by the bookID
        router.HandleFunc("/books/{bookid}", DeleteBook).Methods("DELETE")
    // Delete all books
        router.HandleFunc("/books/", DeleteBooks).Methods("DELETE")
    // serve the app
        fmt.Println("Server at 8080")
    log.Fatal(http.ListenAndServe(":8000", router))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;If the code triggers any of the callback functions without checking, the user has the ability to create, delete, or perform any other action. This code is vulnerable to Broken Access Control. &lt;/p&gt;
&lt;h3&gt;
  
  
  Cryptography
&lt;/h3&gt;

&lt;p&gt;Read: &lt;a href="https://docs.google.com/presentation/d/1gMvkF-Tew1H9oF3Lh2IeQpOkk3bzSpE_TUj00hoztBE/edit#slide=id.g228b0426239_0_3201" rel="noopener noreferrer"&gt;https://docs.google.com/presentation/d/1gMvkF-Tew1H9oF3Lh2IeQpOkk3bzSpE_TUj00hoztBE/edit#slide=id.g228b0426239_0_3201&lt;/a&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Block ciphers can only encrypt a fixed size of data. To encrypt more, one needs a block cipher mode of operation&lt;/li&gt;
&lt;li&gt;Unfortunately, most modes are insecure: &lt;strong&gt;ECB, CBC, CTR, CFB,&lt;/strong&gt; etc. Depending on the usage, you can easily recover or modify the plaintext&lt;/li&gt;
&lt;li&gt;The most common stream cipher &lt;strong&gt;RC4&lt;/strong&gt; also allows you to modify, and, in certain cases (WEP), recover the plaintext&lt;/li&gt;
&lt;/ul&gt;
&lt;h4&gt;
  
  
  Hashing
&lt;/h4&gt;

&lt;p&gt;Make sure that the hashing function is secure against &lt;a href="https://en.wikipedia.org/wiki/Preimage_attack" rel="noopener noreferrer"&gt;Preimage attack&lt;/a&gt;, &lt;a href="https://en.wikipedia.org/wiki/Birthday_attack" rel="noopener noreferrer"&gt;Birthday attack&lt;/a&gt;, ...etc. A list of insecure hash algorithms: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/MD2_(hash_function)" rel="noopener noreferrer"&gt;MD2&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/MD4" rel="noopener noreferrer"&gt;MD4&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/MD5" rel="noopener noreferrer"&gt;MD5&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/SHA-1#SHA-0" rel="noopener noreferrer"&gt;SHA-0&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/SHA-1" rel="noopener noreferrer"&gt;SHA-1&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://en.wikipedia.org/wiki/Panama_(cryptography)" rel="noopener noreferrer"&gt;Panama&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/HAVAL" rel="noopener noreferrer"&gt;HAVAL&lt;/a&gt; (disputable security, collisions found for HAVAL-128)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/Tiger_(hash_function)" rel="noopener noreferrer"&gt;Tiger&lt;/a&gt; (disputable, weaknesses found)&lt;/li&gt;
&lt;li&gt;
&lt;a href="https://en.wikipedia.org/wiki/SipHash" rel="noopener noreferrer"&gt;SipHash&lt;/a&gt; (it is not a cryptographic hash function)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;List of secure hashing functions: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;SHA-2, SHA-256, SHA-512&lt;/li&gt;
&lt;li&gt;SHA-3, SHA3-256, SHA3-512, Keccak-256&lt;/li&gt;
&lt;li&gt;BLAKE2 / BLAKE2s / BLAKE2b&lt;/li&gt;
&lt;li&gt;RIPEMD-160 &lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
        "crypto/md5"
        "crypto/sha256"
        "fmt"
        "io"

        "golang.org/x/crypto/blake2s"
)

func main() {
        h_md5 := md5.New() // insecure 
        h_sha := sha256.New() // secure but not for password without salt
        h_blake2s, _ := blake2s.New256(nil) // secure 
        io.WriteString(h_md5, "Welcome to Go Language Secure Coding Practices")
        io.WriteString(h_sha, "Welcome to Go Language Secure Coding Practices")
        io.WriteString(h_blake2s, "Welcome to Go Language Secure Coding Practices")
        fmt.Printf("MD5 : %x\n", h_md5.Sum(nil))
        fmt.Printf("SHA256 : %x\n", h_sha.Sum(nil))
        fmt.Printf("Blake2s-256: %x\n", h_blake2s.Sum(nil))
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h4&gt;
  
  
  Pseudo-random generators
&lt;/h4&gt;

&lt;p&gt;Generating random numbers is not obvious as it seems. For example, &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main
import (
        "fmt"
        "math/rand"
)
func main() {
        fmt.Println("Random Number: ", rand.Intn(1984))
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Running this code several times will show the following output: &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ for i in {1..5}; do go run rand.go; done
Random Number: 1825
Random Number: 1825
Random Number: 1825
Random Number: 1825
Random Number: 1825
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Why does it generate the same value every time?&lt;br&gt;&lt;br&gt;
Because Go's &lt;code&gt;math/rand&lt;/code&gt; is a deterministic pseudo-random number generator. Similar to many others, it uses a source, called a Seed. This Seed is solely responsible for the randomness of the deterministic pseudo-random number generator. If it is known or predictable, the same will happen in generated number sequence. This behavior could be fixed easily by using the &lt;code&gt;math/rand&lt;/code&gt; Seed funciton. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;❗️&lt;code&gt;math/rand&lt;/code&gt; is not safe to generate tokens, passwords, keys and other random values.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://pkg.go.dev/crypto/rand" rel="noopener noreferrer"&gt;rand package - crypto/rand - Go Packages&lt;/a&gt; must be used to generate random values instead of &lt;code&gt;math/rand&lt;/code&gt;. &lt;/p&gt;
&lt;h3&gt;
  
  
  Error Handling and Logging
&lt;/h3&gt;
&lt;h4&gt;
  
  
  Error handling
&lt;/h4&gt;

&lt;p&gt;When dealing with error logs, developers should ensure no sensitive information is disclosed in the error responses, as well as guarantee that no error handlers leak information (e.g. debugging, or stack trace information).&lt;/p&gt;
&lt;h4&gt;
  
  
  Logging
&lt;/h4&gt;

&lt;p&gt;All logging should be implemented by a master routine on a trusted system, and the developers should also ensure no sensitive data is included in the logs (e.g. passwords, session information, system details, etc.), nor is there any debugging or stack trace information. Additionally, logging should cover both successful and unsuccessful security events, with an emphasis on important log event data.&lt;br&gt;
An example of this is logging Access Tokens of users in OAuth flow. &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;OpenConfigPost("/passport/path/to/function/v2/", antispam(this), open.AccessTokenHandlerV2),

func AccessTokenHandlerV2(ctx *gin.Context) {
    accessTokenParam, err := oauth2.GetAccessTokenRequestParam(ctx)
    logs.CtxInfo(ctx, "[AccessTokenHandlerV2] %v", oauth2.GetRequestString(accessTokenParam))
    /* ... */
    token, perr := rpcHandlers.PassportOpenService.GetAccessTokenV2(ctx,
        accessTokenParam.GetClientKey(), accessTokenParam.GetClientSecret(),
        accessTokenParam.GetAuthorizationCode(), accessTokenParam.GetGrantType(),
        accessTokenParam.RedirectURI, accessTokenParam.GetAppId())
    logs.CtxInfo(ctx, "[GetAccessTokenV2] %v", token.String())
}

type AccessTokenRequestParam struct {
    ClientKey         string `json:"client_key"`
    GrantType         string `json:"grant_type"`
    ClientSecret      string `json:"client_secret"`
    AuthorizationCode string `json:"code"`
    RedirectURI       string `json:"redirect_uri"`
    AppId             int32
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The code above was storing the &lt;code&gt;ClientSecret&lt;/code&gt; and &lt;code&gt;AuthorizationCode&lt;/code&gt; in the log file, which is insecure practice. &lt;br&gt;
Important event data most commonly refers to all:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;input validation failures. &lt;/li&gt;
&lt;li&gt;Authentication attempts, especially failures. &lt;/li&gt;
&lt;li&gt;Access control failures. &lt;/li&gt;
&lt;li&gt;Apparent tampering events, including unexpected changes to state data.&lt;/li&gt;
&lt;li&gt;Attempts to connect with invalid or expired session tokens. &lt;/li&gt;
&lt;li&gt;System exceptions. &lt;/li&gt;
&lt;li&gt;Administrative functions, including changes to security configuration settings. &lt;/li&gt;
&lt;li&gt;Backend TLS connection failures and cryptographic module failures.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  CSRF - Cross-Site Request Forgery
&lt;/h3&gt;

&lt;p&gt;Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. &lt;br&gt;
Let's say that &lt;a href="http://www.foo.com/" rel="noopener noreferrer"&gt;foo.com&lt;/a&gt; uses HTTP GET requests to set the account's recovery email as shown:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;GET https://foo.com/account/recover?email=me@somehost.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;ol&gt;
&lt;li&gt;The victim is authenticated at &lt;a href="https://foo.com" rel="noopener noreferrer"&gt;https://foo.com&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Attacker sends a chat message to the victim with the following link:
&lt;a href="https://foo.com/account/recover?email=me@attacker.com" rel="noopener noreferrer"&gt;https://foo.com/account/recover?email=me@attacker.com&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Victim's account recovery email address is changed to &lt;a href="mailto:me@attacker.com"&gt;me@attacker.com&lt;/a&gt; , giving the attacker full control over it.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The following code is vulnerable to CSRF &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
        "net/http"
)

func main() {
        r := mux.NewRouter()
        r.HandleFunc("/signup", ShowSignupForm)
        r.HandleFunc("/signup/post", SubmitSignupForm)
        http.ListenAndServe(":8000") // No CSRF protection middleware
}
func ShowSignupForm(w http.ResponseWriter, r *http.Request) {

}
func SubmitSignupForm(w http.ResponseWriter, r *http.Request) {
         // Do Stuff 
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Regular Expressions
&lt;/h3&gt;

&lt;p&gt;Regular Expressions are a powerful tool that's widely used to perform searches and validations. Writing ReGex is a hard task and many developers make mistakes while writing it that could lead to security issues.&lt;/p&gt;
&lt;h4&gt;
  
  
  ReDoS
&lt;/h4&gt;

&lt;p&gt;Regular Expression Denial of Service (ReDoS) is an algorithmic complexity attack that provokes a Denial of Service (DoS). ReDos attacks are caused by a regular expression that takes a very long time to be evaluated, exponentially related to input size. This exceptionally long time in the evaluation process is due to the implementation of the regular expression in use, for example, recursive backtracking ones. &lt;br&gt;
To fully understand the ReDos attack, please read the following article: &lt;a href="https://blog.doyensec.com/2021/03/11/regexploit.html" rel="noopener noreferrer"&gt;https://blog.doyensec.com/2021/03/11/regexploit.html&lt;/a&gt; &lt;br&gt;
To detect evil regex use this website: &lt;a href="https://devina.io/redos-checker" rel="noopener noreferrer"&gt;https://devina.io/redos-checker&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvtxp9jcsiinmmh3xm28q.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fvtxp9jcsiinmmh3xm28q.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h4&gt;
  
  
  Faulty regexes
&lt;/h4&gt;

&lt;p&gt;Regex is used for a lot of security checks such as: &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Firewall rules&lt;/li&gt;
&lt;li&gt;Input validation&lt;/li&gt;
&lt;li&gt;Malware detection &lt;/li&gt;
&lt;li&gt;... &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Incorrectly deployed regex may cause security issues. For instance, &lt;br&gt;
&lt;strong&gt;SSRF protection via a blacklist&lt;/strong&gt;&lt;br&gt;
The following regex is being used to detect internal IP addresses &lt;code&gt;^http?://(127\.|10\.|192\.168\.).*$&lt;/code&gt;&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "bytes"
    "fmt"
    "regexp"
)

func main() {

    match, _ := regexp.MatchString("^http?://(127\.|10\.|192\.168\.).*$", "https://0.0.0.0")
    fmt.Println(match)

}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;It fails to match a case which is &lt;code&gt;0.0.0.0&lt;/code&gt; that is the local IP. Learn regex in order to find wrongly configured regex. &lt;br&gt;
Another example, &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package main

import (
    "bytes"
    "fmt"
    "regexp"
)
func main() {
    path := "[USER_INPUT]"  
    match, _ := regexp.MatchString("^[\a-zA-Z0-9_]*", url)
    if match {
    // Send request 
      var url = "https://api.github.com" + path;
     ... 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;The URL &lt;a href="https://api.github.com" rel="noopener noreferrer"&gt;https://api.github.com&lt;/a&gt; does not end with a &lt;code&gt;/&lt;/code&gt;. An attacker can thus send the request to any server via path=.&lt;a href="https://attacker.com/hello," rel="noopener noreferrer"&gt;attacker.com/hello&lt;/a&gt;, resulting in &lt;a href="https://api.github.com.attacker.com/hello" rel="noopener noreferrer"&gt;https://api.github.com.attacker.com/hello&lt;/a&gt;. When an attacker uses this to redirect the request to their server, the &lt;code&gt;Authorization&lt;/code&gt; header gets leaked.&lt;br&gt;
To perform this attack, &lt;code&gt;path&lt;/code&gt; must match the regular expression &lt;code&gt;^[/a-zA-Z0-9_]*&lt;/code&gt;. Looking at the regex, we see that the character &lt;code&gt;*&lt;/code&gt; is a greedy quantifier, indicating that any amount of matches is allowed, including zero. The payload .&lt;a href="https://attacker.com/hello" rel="noopener noreferrer"&gt;attacker.com/hello&lt;/a&gt; does not match the pattern &lt;code&gt;^[/a-zA-Z0-9_]*&lt;/code&gt;, but since zero matches are allowed by the &lt;code&gt;*&lt;/code&gt; quantifier, an attacker can use an arbitrary string as a payload.&lt;/p&gt;
&lt;h2&gt;
  
  
  Checklist
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;RCE

&lt;ul&gt;
&lt;li&gt;Anywhere that a system command is being executed&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exec.Command()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exec.CommandContext()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;syscall.Exec()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;os.StartProcess()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;exec.Cmd()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;SQL injection

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;String concatenation:&lt;/strong&gt; Plus operator,String append, join() function, Sprintf() method, Bytes buffer method, Strings builder method, and Repeat() Method. &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Vulnerable 3rd-Party Modules 

&lt;ul&gt;
&lt;li&gt;Use Snyk &lt;a href="https://docs.snyk.io/getting-started/quickstart" rel="noopener noreferrer"&gt;https://docs.snyk.io/getting-started/quickstart&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;XSS

&lt;ul&gt;
&lt;li&gt;Using the text/template package &lt;/li&gt;
&lt;li&gt;Dangrous functions: &lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.HTML()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.HTMLAttr()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.CSS()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.JS()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.JSStr()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.Srcset()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;template.URL()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;fmt.Fprintf()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;io.WriteString()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;writer.Write()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;SSRF

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;http.X&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;client.X&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;File inclusion

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ioutil.ReadFile()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;filepath.Join()&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;filepath.Clean()&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;XXE

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;libxml2&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;parser.XMLParseNoEnt &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Auth

&lt;ul&gt;
&lt;li&gt;Password storing &lt;/li&gt;
&lt;li&gt;Logic &lt;/li&gt;
&lt;li&gt;Session&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Unpredictable&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;New after login&lt;/em&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Access control 

&lt;ul&gt;
&lt;li&gt;Logic &lt;/li&gt;
&lt;li&gt;Understand the task in hand and the threat model of it.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Cryptgraphy

&lt;ul&gt;
&lt;li&gt;Hashing&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Insecure algorithms such as MD5, SHA-1,...etc&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;No salt or fixed salt&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;Pseudo-Random Generators &lt;/li&gt;
&lt;li&gt;
&lt;em&gt;Math/rand to generate random numbers&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;ECB, CBC, CTR, and CFB&lt;/li&gt;
&lt;li&gt;AES-GCM&lt;/li&gt;
&lt;li&gt;Password-based Encryption (RFC 2898) &lt;/li&gt;
&lt;li&gt;RSA PKCS v1.5 Encryption&lt;/li&gt;
&lt;li&gt;ECDSA&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Error Handling and Logging

&lt;ul&gt;
&lt;li&gt;Error handling&lt;/li&gt;
&lt;li&gt;&lt;em&gt;No sensitive information is disclosed in error responses&lt;/em&gt;&lt;/li&gt;
&lt;li&gt;
&lt;em&gt;No debug information&lt;/em&gt; &lt;/li&gt;
&lt;li&gt;Logging&lt;/li&gt;
&lt;li&gt;&lt;em&gt;Ensure no sensitive data is included in the logs (e.g. passwords, session information, system details, etc.&lt;/em&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;CSRF

&lt;ul&gt;
&lt;li&gt;No CSRF protection middleware &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;Regular expression

&lt;ul&gt;
&lt;li&gt;Fuzz &lt;/li&gt;
&lt;li&gt;Test evil regex: &lt;a href="https://devina.io/redos-checker" rel="noopener noreferrer"&gt;https://devina.io/redos-checker&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;Understand the expected output &lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Study materials
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://github.com/OWASP/Go-SCP/blob/master/dist/go-webapp-scp.pdf" rel="noopener noreferrer"&gt;https://github.com/OWASP/Go-SCP/blob/master/dist/go-webapp-scp.pdf&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://www.ctfiot.com/47181.html" rel="noopener noreferrer"&gt;https://www.ctfiot.com/47181.html&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;
&lt;a href="https://breakandpray.com/analyzing-a-broken-authentication-vulnerability-in-golang/" rel="noopener noreferrer"&gt;https://breakandpray.com/analyzing-a-broken-authentication-vulnerability-in-golang/&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://docs.guardrails.io/docs/vulnerabilities/go/insecure_use_of_dangerous_function" rel="noopener noreferrer"&gt;https://docs.guardrails.io/docs/vulnerabilities/go/insecure_use_of_dangerous_function&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.stackhawk.com/blog/golang-command-injection-examples-and-prevention/" rel="noopener noreferrer"&gt;https://www.stackhawk.com/blog/golang-command-injection-examples-and-prevention/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.sonarsource.com/knowledge/code-challenges/advent-calendar-2022/" rel="noopener noreferrer"&gt;https://www.sonarsource.com/knowledge/code-challenges/advent-calendar-2022/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.elttam.com/blog/golang-codereview/" rel="noopener noreferrer"&gt;https://www.elttam.com/blog/golang-codereview/&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://gorm.io/docs/security.html" rel="noopener noreferrer"&gt;https://gorm.io/docs/security.html&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Sponsored by &lt;a href="https://www.marscode.com/?utm_source=dev.to"&gt;MarsCode&lt;/a&gt;&lt;br&gt;
Welcome to join our &lt;a href="https://discord.gg/marscode" rel="noopener noreferrer"&gt;Discord&lt;/a&gt; to discuss your ideas with us.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__user ltag__user__id__8972"&gt;
  &lt;a href="/marscode" class="ltag__user__link profile-image-link"&gt;
    &lt;div class="ltag__user__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F8972%2F635fc011-c62f-4cbc-b6cb-f1a1c61e9d11.jpeg" alt="marscode image"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;div class="ltag__user__content"&gt;
    &lt;h2&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;MarsCode&lt;/a&gt;
      Follow
    &lt;/h2&gt;
    &lt;div class="ltag__user__summary"&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;
        MarsCode provides an AI-powered  IDE and an AI extension to assist your programming tasks.
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;


</description>
      <category>go</category>
    </item>
    <item>
      <title>5 Javascript Tips You Should Know</title>
      <dc:creator>Dawn Zhao</dc:creator>
      <pubDate>Mon, 19 Aug 2024 08:28:31 +0000</pubDate>
      <link>https://forem.com/marscode/5-javascript-tips-you-should-know-23db</link>
      <guid>https://forem.com/marscode/5-javascript-tips-you-should-know-23db</guid>
      <description>&lt;p&gt;Written by Joab Chua&lt;/p&gt;

&lt;h2&gt;
  
  
  1. Console.log
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Add colour to your console log&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Stop doing just this! ❌&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz0lan34m6fvzyt1foyfx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fz0lan34m6fvzyt1foyfx.png" alt="Image description" width="579" height="253"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7v4bnzsszp8tyg75cdd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr7v4bnzsszp8tyg75cdd.png" alt="Image description" width="277" height="63"&gt;&lt;/a&gt;&lt;br&gt;
Try this instead. ✅&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb1sj6i0aje6h1sp3b71p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fb1sj6i0aje6h1sp3b71p.png" alt="Image description" width="679" height="310"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzyxsefhq6r5carwdb9qm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzyxsefhq6r5carwdb9qm.png" alt="Image description" width="331" height="127"&gt;&lt;/a&gt;&lt;br&gt;
But if you have an array of objects, try this would be even better 😎&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fitoo83muophjwbu8p4rh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fitoo83muophjwbu8p4rh.png" alt="Image description" width="558" height="202"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhw512oabzuax9qwiolq8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhw512oabzuax9qwiolq8.png" alt="Image description" width="660" height="198"&gt;&lt;/a&gt;&lt;br&gt;
If you want to measure how fast certain operations run in your code, try this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9n5920pu0jgkqb45gwa9.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F9n5920pu0jgkqb45gwa9.png" alt="Image description" width="327" height="276"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxbahd6udwh6b2suzetf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Frxbahd6udwh6b2suzetf.png" alt="Image description" width="214" height="26"&gt;&lt;/a&gt;&lt;br&gt;
Do console.time and console.timeEnd to measure the time taken in the browser console.&lt;br&gt;
Lastly, if you want to trace your code and its execution sequence, try this.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwq0s80on798n6vtzsd9e.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fwq0s80on798n6vtzsd9e.png" alt="Image description" width="325" height="219"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1313gj5e60346q22ucqj.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F1313gj5e60346q22ucqj.png" alt="Image description" width="544" height="590"&gt;&lt;/a&gt;&lt;br&gt;
You will be able to see tonnes of info that you need to debug your application.&lt;/p&gt;
&lt;h2&gt;
  
  
  2. Object de-structuring
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq5tq1i7wpjpfgojlmmlx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq5tq1i7wpjpfgojlmmlx.png" alt="Image description" width="348" height="274"&gt;&lt;/a&gt;&lt;br&gt;
Did it happened to you before that you only need a few variables in the object but you are being passed the full object and using it in this conventional way?&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Filexa935wd26177utd19.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Filexa935wd26177utd19.png" alt="Image description" width="678" height="228"&gt;&lt;/a&gt;&lt;br&gt;
Repeatedly using the human object declaration in your function? Don’t do this. Use ES6 object de-structuring instead. ✅&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh904n7rnj0yt7hrlcnq2.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh904n7rnj0yt7hrlcnq2.png" alt="Image description" width="720" height="168"&gt;&lt;/a&gt;&lt;br&gt;
De-structure the variables that you need to use in the function arguments. Alternatively, you can de-structure inside the function itself.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm7569jre4q5heegsczot.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm7569jre4q5heegsczot.png" alt="Image description" width="720" height="183"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  3. Template Literal
&lt;/h2&gt;

&lt;p&gt;❌ Don’t do this when you are trying to piece your variables with string.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpbi59jtr4bpj4uq5o8jp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpbi59jtr4bpj4uq5o8jp.png" alt="Image description" width="492" height="196"&gt;&lt;/a&gt;&lt;br&gt;
Do this instead. ✅&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnj3d2a1pxch252jv9bbb.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fnj3d2a1pxch252jv9bbb.png" alt="Image description" width="611" height="193"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  4. Spread operator
&lt;/h2&gt;

&lt;p&gt;Let’s say you have 2 object and you want to combined them or assign some of the properties of 1 object to another. Traditionally, we will do this.&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0gwb0qs3gc4n1g1yo4k.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fk0gwb0qs3gc4n1g1yo4k.png" alt="Image description" width="539" height="323"&gt;&lt;/a&gt;&lt;br&gt;
There is technically nothing wrong with that, except that you are actually mutating your object. Try this instead. ✅&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzrv0gqdo7zgoo8yv0ajr.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzrv0gqdo7zgoo8yv0ajr.png" alt="Image description" width="449" height="147"&gt;&lt;/a&gt;&lt;br&gt;
Best thing of spread operator is that it works for array as well. 😎&lt;br&gt;
Instead of this.&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr6ihh74wcsamhikfj627.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fr6ihh74wcsamhikfj627.png" alt="Image description" width="468" height="197"&gt;&lt;/a&gt;&lt;br&gt;
Do this instead.&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faiush6w0romr3twmsds1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Faiush6w0romr3twmsds1.png" alt="Image description" width="494" height="113"&gt;&lt;/a&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  5. loops
&lt;/h2&gt;

&lt;p&gt;Are you guilty of doing for loop this way to calculate the total amount of the cost in an array? Stop doing this. ❌&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd92585pyxx9333g0c7lf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fd92585pyxx9333g0c7lf.png" alt="Image description" width="533" height="407"&gt;&lt;/a&gt;&lt;br&gt;
Start to change your style to this instead.&lt;br&gt;
&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4p26w8o9gg0svwlx6cw8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4p26w8o9gg0svwlx6cw8.png" alt="Image description" width="653" height="177"&gt;&lt;/a&gt;&lt;br&gt;
Clean and lean. Job done! ✅&lt;/p&gt;
&lt;h2&gt;
  
  
  Summary
&lt;/h2&gt;

&lt;p&gt;Hope that these few tips will guide you along to write better, cleaner and leaner code.&lt;/p&gt;

&lt;p&gt;Sponsored by &lt;a href="https://www.marscode.com/?utm_source=dev.to"&gt;MarsCode&lt;/a&gt;&lt;br&gt;
Welcome to join our &lt;a href="https://discord.gg/marscode" rel="noopener noreferrer"&gt;Discord&lt;/a&gt; to discuss your ideas with us.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__user ltag__user__id__8972"&gt;
  &lt;a href="/marscode" class="ltag__user__link profile-image-link"&gt;
    &lt;div class="ltag__user__pic"&gt;
      &lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F8972%2F635fc011-c62f-4cbc-b6cb-f1a1c61e9d11.jpeg" alt="marscode image"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;div class="ltag__user__content"&gt;
    &lt;h2&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;MarsCode&lt;/a&gt;
      Follow
    &lt;/h2&gt;
    &lt;div class="ltag__user__summary"&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;
        MarsCode provides an AI-powered  IDE and an AI extension to assist your programming tasks.
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;


</description>
      <category>javascript</category>
      <category>programming</category>
      <category>development</category>
    </item>
    <item>
      <title>Unlock the Power of Real-Time UI: A Beginner's Guide to Streaming Data with React.js, gRPC, Envoy, and Golang</title>
      <dc:creator>Dawn Zhao</dc:creator>
      <pubDate>Thu, 08 Aug 2024 03:36:52 +0000</pubDate>
      <link>https://forem.com/marscode/unlock-the-power-of-real-time-ui-a-beginners-guide-to-streaming-data-with-reactjs-grpc-envoy-and-golang-271p</link>
      <guid>https://forem.com/marscode/unlock-the-power-of-real-time-ui-a-beginners-guide-to-streaming-data-with-reactjs-grpc-envoy-and-golang-271p</guid>
      <description>&lt;p&gt;Written by Naveen M&lt;/p&gt;

&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;As part of our Kubernetes platform team, we face the constant challenge of providing real-time visibility into user workloads. From monitoring resource usage to tracking Kubernetes cluster activity and application status, there are numerous open-source solutions available for each specific category. However, these tools are often scattered across different platforms, resulting in a fragmented user experience. To address this issue, we have embraced the power of server-side streaming, enabling us to deliver live resource usage, Kubernetes events, and application status as soon as users access our platform portal.&lt;/p&gt;

&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;By implementing server-side streaming, we can seamlessly stream data to the user interface, providing up-to-date information without the need for manual refreshes or constant API calls. This approach revolutionizes user experience, allowing users to instantly visualize the health and performance of their workloads in a unified and simplified manner. Whether it's monitoring resource utilization, staying informed about Kubernetes events, or keeping tabs on application status, our server-side streaming solution brings together all the critical information in a single, real-time dashboard, but this will be applicable to anyone who wants to provide live streaming data to the user interface.&lt;br&gt;
Gone are the days of navigating through multiple tools and platforms to gather essential insights. With our streamlined approach, users can access a comprehensive overview of their Kubernetes environment the moment they land on our platform portal. By harnessing the power of server-side streaming, we have transformed the way users interact with and monitor their workloads, making their experience more efficient, intuitive, and productive.&lt;br&gt;
Through our blog series, we aim to guide you through the intricacies of setting up server-side streaming with technologies such as React.js, Envoy, gRPC, and Golang.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;There are three main components involved in this project:&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;1. The backend, which is developed using Golang and utilizes gRPC server-side streaming to transmit data.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;2. The Envoy proxy, which is responsible for making the backend service accessible to the outside world.&lt;/strong&gt;&lt;br&gt;
&lt;strong&gt;3. The frontend, which is built using React.js and employs grpc-web to establish communication with the backend.&lt;/strong&gt;&lt;br&gt;
The series is divided into multiple parts to accommodate the diverse language preferences of developers. If you're interested specifically in the role of Envoy in streaming or want to learn about deploying an Envoy proxy in Kubernetes, you can jump to the second part (Envoy as a frontend proxy in Kubernetes) and explore that aspect or just interested in the front end part, then you can just check out the front end part of the blog.&lt;br&gt;
In this initial part, we'll focus on the easiest segment of the series: "How to Set Up gRPC Server-Side Streaming with Go." We are going to show sample applications with server side streaming. Fortunately, there is a wealth of content available on the internet for this topic, tailored to your preferred programming language.&lt;/p&gt;
&lt;h2&gt;
  
  
  PART 1: How to Set Up gRPC Server-Side Streaming with Go
&lt;/h2&gt;

&lt;p&gt;It's time to put our plan into action! Assuming you have a basic understanding of the following concepts, let's dive right into the implementation:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;gRPC&lt;/strong&gt;: It's a communication protocol that allows the client and server to exchange data efficiently.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Server-side streaming&lt;/strong&gt;: This feature is particularly useful when the server needs to send a large amount of data to the client. By using server-side streaming, the server can split the data into smaller portions and send them one by one. The client can then choose to stop receiving data if it has received enough or if it has been waiting for too long.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now, let's start with code implementation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 1: Create the Proto File&lt;/strong&gt;&lt;br&gt;
To begin, we need to define a protobuf file that will be used by both the client and server sides. Here's a simple example:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

syntax = "proto3";

package protobuf;

service StreamService {
  rpc FetchResponse (Request) returns (stream Response) {}
}

message Request {
  int32 id = 1;
}

message Response {
  string result = 1;
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;In this proto file, we have a single function called &lt;code&gt;FetchResponse&lt;/code&gt; that takes a &lt;code&gt;Request&lt;/code&gt; parameter and returns a stream of &lt;code&gt;Response&lt;/code&gt; messages.&lt;/p&gt;
&lt;h2&gt;
  
  
  Step 2: Generate the Protocol Buffer File
&lt;/h2&gt;

&lt;p&gt;Before we proceed, we need to generate the corresponding pb file that will be used in our Go program. Each programming language has its own way of generating the protocol buffer file. In Go, we will be using the &lt;code&gt;protoc&lt;/code&gt; library.&lt;br&gt;
If you haven't installed it yet, you can find the installation guide provided by Google.&lt;br&gt;
To generate the protocol buffer file, run the following command:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

protoc --go_out=plugins=grpc:. *.proto


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;Now, we have the &lt;code&gt;data.pb.go&lt;/code&gt; file ready to be used in our implementation.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Step 3: Server side implementation&lt;/strong&gt;&lt;br&gt;
To create the server file, follow the code snippet below:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

package main

import (
        "fmt"
        "log"
        "net"
        "sync"
        "time"

        pb "github.com/mnkg561/go-grpc-server-streaming-example/src/proto"
        "google.golang.org/grpc"
)

type server struct{}

func (s server) FetchResponse(in pb.Request, srv pb.StreamService_FetchResponseServer) error {

        log.Printf("Fetching response for ID: %d", in.Id)

        var wg sync.WaitGroup
        for i := 0; i &amp;lt; 5; i++ {
                wg.Add(1)
                go func(count int) {
                        defer wg.Done()

                        time.Sleep(time.Duration(count)  time.Second)
                        resp := pb.Response{Result: fmt.Sprintf("Request #%d for ID: %d", count, in.Id)}
                        if err := srv.Send(&amp;amp;resp); err != nil {
                                log.Printf("Error sending response: %v", err)
                        }
                        log.Printf("Finished processing request number: %d", count)
                }(i)
        }

        wg.Wait()
        return nil
}

func main() {
        lis, err := net.Listen("tcp", ":50005")
        if err != nil {
                log.Fatalf("Failed to listen: %v", err)
        }

        s := grpc.NewServer()
        pb.RegisterStreamServiceServer(s, server{})

        log.Println("Server started")
        if err := s.Serve(lis); err != nil {
                log.Fatalf("Failed to serve: %v", err)
        }
}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;p&gt;In this server file, I have implemented the &lt;code&gt;FetchResponse&lt;/code&gt; function, which receives a request from the client and sends a stream of responses back. The server simulates concurrent processing using goroutines. For each request, it streams five responses back to the client. Each response is delayed by a certain duration to simulate different processing times.&lt;br&gt;
The server listens on port 50005 and registers the &lt;code&gt;StreamServiceServer&lt;/code&gt; with the created server. Finally, it starts serving requests and logs a message indicating that the server has started.&lt;br&gt;
Now you have the server file ready to handle streaming requests from clients.&lt;/p&gt;
&lt;h2&gt;
  
  
  Part 2
&lt;/h2&gt;

&lt;p&gt;Stay tuned for Part 2 where we will continue to dive into the exciting world of streaming data and how it can revolutionize your user interface.&lt;/p&gt;

&lt;p&gt;Sponsored by &lt;a href="https://www.marscode.com/?utm_source=dev.to"&gt;MarsCode&lt;/a&gt;&lt;br&gt;
Welcome to join our &lt;a href="https://discord.gg/marscode" rel="noopener noreferrer"&gt;Discord&lt;/a&gt; to discuss your ideas with us.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__user ltag__user__id__8972"&gt;
  &lt;a href="/marscode" class="ltag__user__link profile-image-link"&gt;
    &lt;div class="ltag__user__pic"&gt;
      &lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F8972%2F635fc011-c62f-4cbc-b6cb-f1a1c61e9d11.jpeg" alt="marscode image"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;div class="ltag__user__content"&gt;
    &lt;h2&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;MarsCode&lt;/a&gt;
      Follow
    &lt;/h2&gt;
    &lt;div class="ltag__user__summary"&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;
        MarsCode provides an AI-powered  IDE and an AI extension to assist your programming tasks.
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;


</description>
      <category>programming</category>
      <category>opensource</category>
      <category>react</category>
      <category>go</category>
    </item>
    <item>
      <title>Personal experience sharing on Transitioning from Java to Go</title>
      <dc:creator>Dawn Zhao</dc:creator>
      <pubDate>Fri, 02 Aug 2024 08:26:17 +0000</pubDate>
      <link>https://forem.com/marscode/personal-experience-sharing-on-transitioning-from-java-to-go-12nc</link>
      <guid>https://forem.com/marscode/personal-experience-sharing-on-transitioning-from-java-to-go-12nc</guid>
      <description>&lt;p&gt;Writtern by HaojunFang&lt;/p&gt;

&lt;h2&gt;
  
  
  Background
&lt;/h2&gt;

&lt;p&gt;I still recall when I first started learning programming, a common phrase I used to hear was: "Programming languages are just tools, the programming mindset is what matters most". However, from a practical perspective, the barriers between different languages are pretty significant. (Otherwise, wouldn't the design of these languages be in vain? 😄).&lt;br&gt;
As a former Java developer, I have a high regard for Java. This probably stems from its robust ecosystem and impressive productivity. Java's syntax is clear and concise, easy to learn, and offers a great deal of flexibility and extensibility simultaneously. In addition, Java's virtual machine mechanism allows it to be cross-platform, capable of running on different operating systems, which is a tremendous advantage for developers.&lt;br&gt;
However, considering the current situation, reality compelled me to learn a new language - Golang. Many companies are favoring Go, and its developers tend to have higher salaries. After almost a year of studying, using, and practicing Go, I have garnered some basic insights. I present them in this article with the hope of sharing and discussing them with you all!&lt;/p&gt;
&lt;h2&gt;
  
  
  Why Go
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcas7kuq4afuqkj4hube0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fcas7kuq4afuqkj4hube0.png" alt="Image description" width="800" height="489"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can observe that Go is relatively low on the list, yet many companies still choose Go as their primary development language. This piqued my interest and I aim to understand the reasons behind this.&lt;/p&gt;

&lt;p&gt;After referring to multiple documents, I concluded the following key advantages of the Go language for developers:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Powerful Concurrency: Go's Goroutines and Channels adeptly address the issues related to concurrency and asynchronous programming.&lt;/li&gt;
&lt;li&gt;Straightforward Syntax: Go language's syntax is simpler and easier to learn than Java, which can help reduce development costs.&lt;/li&gt;
&lt;li&gt;Efficient Memory Management: The memory management in Go is more efficient than Java, thus conserving system resources.&lt;/li&gt;
&lt;li&gt;Cross Platform: Go allows for cross-platform compilation, enabling the operation on various operating systems. This makes business expansion and migration more convenient.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Language Features
&lt;/h2&gt;

&lt;p&gt;When it comes to language features, as a former Java developer, a comparison with Java is inevitable:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Go, also known as Golang, is a static, compiled, and concurrent programming language developed by Google. It was designed with simplicity and efficiency in mind. Its features include easy learning curve, efficient concurrency, garbage collection mechanism, and a robust standard library.&lt;/li&gt;
&lt;li&gt;Java, on the other hand, is a widely used object-oriented programming language aiming to "write once, run anywhere". It boasts cross-platform capability, object-oriented characteristics, and a rich, powerful library.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;OOP&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Firstly, Go is not an object-oriented language, but it can simulate object-oriented characteristics using structures and interfaces. In Go, structures hold the same level of importance as classes in object-oriented paradigms. They can contain variables and methods of various types. Object-oriented principles can be achieved through encapsulation, interfaces, and other means.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;em&gt;Object-oriented programming is a paradigm that encapsulates entities with similar features into a unified class form. The properties and methods within the encapsulated classes represent the common characteristics and behaviors among these entities. It primarily encompasses three characteristics: Encapsulation, Inheritance, and Polymorphism.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Encapsulation&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In OOP, the members and methods of a class can be encapsulated, and their visibility can be controlled by access modifiers. In Go, members of a struct are exposed by default, and can be accessed outside of the struct. Strict encapsulation, like in classes, is not available. However, control of whether to export can be handled via the case of the first letter of the attribute (if not exported, it cannot be accessed externally).&lt;br&gt;
&lt;/p&gt;


&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test111

type TestDto struct {
    age  string // Accessible within the package
    Name string // Accessible globally
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;2. Inheritance&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In object-oriented programming languages, object inheritance is used, and in Java, the keyword "extend" is used to achieve this. In Go, inheritance relationships can be implemented using embedded structures.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;package test111

type BaseRespDto struct{
    ReturnCode string
    Returnsg  string
}

type QueryOrderRespDto struct{
    BaseRespDto // After composing an anonymous base structure, the current structure can access the attribute fields of the base structure.

    OrderID     string
    OrderAmount int64
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;3. Polymorphism&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;OOP supports polymorphism, wherein an object can exhibit different behaviors depending on the context. While Go's structs do not directly support polymorphism, a similar effect can be achieved using interfaces. If a type implements all the methods of an interface, it can be assigned to a variable of that interface type. Polymorphism enables programs to automatically select the appropriate method implementation based on the context, thereby enhancing the flexibility and reusability of the code.&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var (
    applePhone *Mobile
)

func init() {
    applePhone = NewMobile("xiaoming", "iPhone 15 Pro MAX", 1111100)
}

type USB interface {
    Storage()
    Charge() string
}

type PlayBoy interface {
    Game(name string)
}

type Mobile struct {
    User  string `json:"user"`
    Brand string `json:"brand"`
    Prise int64  `json:"prise"`
}

func NewMobile(user string, brand string, prise float64) *Mobile {
    return &amp;amp;Mobile{User: user, Brand: brand, Prise: prise}
}

func (m *Mobile) CallUp() {
    fmt.Printf("%s is using 💲%.2f mobile phone to make a call.\n", m.User, m.Prise)
}

func (m *Mobile) Storage() {
    fmt.Printf("%s is using a %s mobile phone to transfer data.\n", m.User, m.Brand)
}

func (m *Mobile) Charge() string {
    return fmt.Sprintf("%s is charging a %s phone.\n", m.User, m.Brand)
}

func (m *Mobile) PlayGame(name string) {
    fmt.Printf("%s is playing the game of '%s'.\n", m.User, name)
}

func TestExample(t *testing.T) {
    applePhone.Storage()
    applePhone.Charge()
    applePhone.PlayGame(applePhone.User)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;strong&gt;Design Philosophy&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Design Characteristics of Go&lt;br&gt;
If you can't find an X feature from other languages in Go, it likely means that this feature is not suitable for Go. For instance, it might affect the compilation speed, clarity of design, or it could make the basic system particularly complex.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ol&gt;
&lt;li&gt;Less is More: If a feature does not provide significant value in solving any problem, Go will not offer it. If a feature is needed, there should be only one way to implement it.&lt;/li&gt;
&lt;li&gt;Interface-Oriented Programming: Go proposes non-intrusive interfaces, rebutting inheritance, virtual functions and their overloading (polymorphism), and eliminating constructors and destructors.&lt;/li&gt;
&lt;li&gt;Orthogonal + Composition: Features of the language are independent of each other, not influencing one another. For instance, types and methods are independent, so are the different types with no subclasses, and packages do not have sub-packages. Different features are loosely coupled through composition.&lt;/li&gt;
&lt;li&gt;Concurrency Support at the Language Level: Concurrency better utilizes multi-cores and offers a robust expressiveness to simulate the real world.&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;
  
  
  Common Pitfalls &amp;amp; Knowledge Points at Syntax Level
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Types&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In addition to the common basic types, Go also has a &lt;code&gt;Func()&lt;/code&gt; type that represents a function. This is somewhat similar to the Supplier functional interface in Java.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Branching Decision&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;switch-case-default&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The switch-case syntax in Go is fundamentally similar to that in Java, with minor distinctions between the two. Let's clarify this with an example:&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Go&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;func main() {
    name := "ddd"
    switch name {
    case "xxxx":
       fmt.Println(name + "1")
    case "ddd":
       fmt.Println(name + "2")
    case "xxxxxx":
       fmt.Println(name + "3")
    default:
       fmt.Println(name + "4")
    }
}

Output Result：
ddd2
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;em&gt;Java&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public static void main(String[] args) {
    testSwitch("name");
}
private static void testSwitch(String var){
    switch (var){
        case "1":
            System.out.println(var+"1");
        case "name":
            System.out.println(var+"2");
        case "3":
            System.out.println(var+"3");
        default:
            System.out.println(var+"4");
    }
}

Output Result
name2
name3
name4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;In Go, case branches do not explicitly need a break or return statement. Once a rule is met, subsequent branches won't be executed. This is due to Go's design philosophy that emphasizes simplicity and efficiency, avoiding unnecessary code redundancy.&lt;br&gt;
When a &lt;code&gt;switch-case&lt;/code&gt; statement in Go encounters a matching &lt;code&gt;case&lt;/code&gt;, it automatically executes all the statements in that &lt;code&gt;case&lt;/code&gt; until it bumps into the next &lt;code&gt;case&lt;/code&gt; or &lt;code&gt;default&lt;/code&gt;. If there is no following &lt;code&gt;case&lt;/code&gt; or &lt;code&gt;default&lt;/code&gt;, the program will continue to execute the following code.&lt;br&gt;
This design approach simplifies the code while preventing errors that can arise from forgetting to add a &lt;code&gt;break&lt;/code&gt; statement within a &lt;code&gt;case&lt;/code&gt;. However, it is crucial to note that if you need to transition to the next &lt;code&gt;case&lt;/code&gt; within a &lt;code&gt;case&lt;/code&gt;, you can use the &lt;code&gt;fallthrough&lt;/code&gt; keyword to achieve this.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Exported Names&lt;/strong&gt;&lt;br&gt;
Go does not have access modifiers like Java's public/private/protected/default. Instead, it uses a simple rule where the capitalization of the first letter determines if a structure/variable/method/function is exported. An exported entity, in this context, refers to whether it can be called/used by external packages.&lt;br&gt;
In Go, identifiers of variables, functions, and structures that start with an uppercase letter can be accessed by code outside their package. In contrast, identifiers starting with lowercase are package-private. This is one of the design principles in Go programming language.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Error and Panic&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The cumbersome error handling logic in Golang is a point of contention for many Java developers. Every error needs to be manually dealt with in the code, often using the classic &lt;code&gt;if err != nil&lt;/code&gt; check.&lt;/li&gt;
&lt;li&gt;Golang's panic mechanism, which leads to process exit, also tends to alarm and frustrate most developers.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;In my understanding, Error in Go is somewhat analogous to RuntimeException in Java. It represents business errors that occur during runtime, which developers can manually handle. On the other hand, Panic in Go is similar to Error in Java, representing system-level errors that cannot be resolved.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Struct Creation&lt;/strong&gt;&lt;br&gt;
👍 In Go, when creating variables of struct types, built-in syntax allows for setting field values, so there's no need to manually write constructors or call a host of set methods for assignment like in Java.&lt;/p&gt;

&lt;p&gt;Generally, there are two methods for creating an empty instance:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;new(T)&lt;/li&gt;
&lt;li&gt;&amp;amp;T{} —— This method is most commonly used.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Value and Reference Pass&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In Golang, all parameters are passed by value, i.e., a clone of the original value. Modifications inside functions/methods do not affect the external value objects. Therefore, it's generally recommended to use pointers as arguments in functions/methods due to a couple of benefits:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Reduces memory usage, since passing by value requires duplication.&lt;/li&gt;
&lt;li&gt;Allows the modification of specific data pointed to by the pointer inside the function.&lt;/li&gt;
&lt;/ol&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Defer Function&lt;/strong&gt;&lt;br&gt;
The purpose of &lt;code&gt;defer&lt;/code&gt; is to postpone the execution of a segment of code, and it's generally used for closing resources or executing necessary finalizing operations. The &lt;code&gt;defer&lt;/code&gt; code block is executed no matter whether there is an error or not, which is similar to the function of the &lt;code&gt;finally&lt;/code&gt; block in Java.&lt;br&gt;
&lt;code&gt;Defer&lt;/code&gt; uses a stack to manage the code that needs to be executed, hence the order of execution of deferred functions is opposite to the order of their declaration - following a "last in, first out" approach.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pitfalls:&lt;/strong&gt;&lt;br&gt;
The value of the parameters in a &lt;code&gt;defer&lt;/code&gt; function is determined at the time of declaring &lt;code&gt;defer&lt;/code&gt;. When declaring a &lt;code&gt;defer&lt;/code&gt; function, there are two ways to reference external variables: as function parameters and as closure references.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;As function parameters, the value is passed to &lt;code&gt;defer&lt;/code&gt; at the time of declaration, and the value is cached. The cached value is used for computation when the &lt;code&gt;defer&lt;/code&gt; is called.&lt;/li&gt;
&lt;li&gt;As closure references, the current value is determined based on the entire context when the &lt;code&gt;defer&lt;/code&gt; function is executed (this method is recommended).&lt;/li&gt;
&lt;/ul&gt;
&lt;h2&gt;
  
  
  Comparison with Java
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Code Style &amp;amp; Coding Conventions&lt;/strong&gt;&lt;br&gt;
Compared with Java, Golang has more stringent coding constraints. If such rules are not followed, your code might not be able to compile. The specific constraints are as follows:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;A defined variable must be used or it can be replaced with &lt;code&gt;_&lt;/code&gt; to denote it can be ignored.&lt;/li&gt;
&lt;li&gt;Imported packages must be used.&lt;/li&gt;
&lt;li&gt;Braces must start at the end of the current line, and cannot be placed on a new line.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Access Control&lt;/strong&gt;&lt;br&gt;
Compared to Java, Golang's access control is straightforward - it only requires distinguishing between uppercase and lowercase initials.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Instance/Object Declaration and Creation&lt;/strong&gt;&lt;br&gt;
In Java, almost all object instances are created using the &lt;code&gt;new&lt;/code&gt; keyword. On the other hand, in Golang, it's simpler - you just need to use &lt;code&gt;a := T{}&lt;/code&gt; or &lt;code&gt;a := &amp;amp;T{}&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Difference between Structs and Classes&lt;/strong&gt;&lt;br&gt;
In Java, classes are foundational, and all logic relies on classes for existence.&lt;br&gt;
However, in Golang, there is no concept of a class. The closest definition is a struct. Still, Golang's struct basically serves as a data carrier. In Golang, functions are the basis and can exist independent of structs. Also, in Java, invocations are driven based on classes or objects, whereas in Golang, function/method calls are partitioned by packages.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Functions and Methods&lt;/strong&gt;&lt;br&gt;
In Java, the term 'function' might be rarely used because all methods rely on the existence of class objects (this gap was filled after Java 8 with functional interfaces). In Golang, however, functions are first-class citizens, and methods are just special functions which include the current receiver as an implicit first parameter.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Pointers&lt;/strong&gt;&lt;br&gt;
For Java developers, pointers may appear slightly unfamiliar. You can consider it equivalent to object references in Java. Both Java and Golang pass values when making method calls. In Java, if a reference type (object, array, etc.) is passed, its pointer will be copied and passed. In Golang, you must explicitly pass the pointer of the struct; otherwise, you are just passing a copy of the object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;AOP/IOC/Transactional Declaration&lt;/strong&gt;&lt;br&gt;
One of the aspects making Golang challenging for Java developers is the lack of AOP (Aspect-Oriented Programming) capabilities. For example, to start a DB transaction in Golang, you need to manually write &lt;code&gt;tx begin&lt;/code&gt;, &lt;code&gt;tx end&lt;/code&gt;, &lt;code&gt;tx rollback&lt;/code&gt;, and obtain the &lt;code&gt;tx&lt;/code&gt; instance pointer. You also need to ensure that &lt;code&gt;tx&lt;/code&gt; is not written incorrectly within a transaction, otherwise deadlocks and inconsistent queries might occur.&lt;br&gt;
In contrast, in Java - thanks to AOP capabilities and the Spring framework - developers generally just need to focus on specific business logic and decide where to add a &lt;code&gt;@Transactional&lt;/code&gt; annotation on a particular repo method. The subsequent transaction operations are managed by the framework.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;I remember when I first started writing requirements, I encountered an embarrassing situation due to my lack of understanding. I couldn't query the data right after inserting it in the same transaction, which stalled my unit test for quite some time. Eventually, I found out that the SQL query didn't use the same &lt;code&gt;tx&lt;/code&gt; connection.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;IOC/DI (Inversion of Control/Dependency Injection) essentially implies the handing over of object creation and dependency injection to Spring during application startup in Java. Although Golang has the Wire injection framework, developers essentially need to predefine the instantiation rules, which could be viewed as a compile-time capability.&lt;/p&gt;

&lt;p&gt;Sponsored by &lt;a href="https://www.marscode.com/?utm_source=dev.to"&gt;MarsCode&lt;/a&gt;&lt;br&gt;
Welcome to join our &lt;a href="https://discord.gg/marscode" rel="noopener noreferrer"&gt;Discord&lt;/a&gt; to discuss your ideas with us.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag__user ltag__user__id__8972"&gt;
  &lt;a href="/marscode" class="ltag__user__link profile-image-link"&gt;
    &lt;div class="ltag__user__pic"&gt;
      &lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Forganization%2Fprofile_image%2F8972%2F635fc011-c62f-4cbc-b6cb-f1a1c61e9d11.jpeg" alt="marscode image"&gt;
    &lt;/div&gt;
  &lt;/a&gt;
  &lt;div class="ltag__user__content"&gt;
    &lt;h2&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;MarsCode&lt;/a&gt;
      Follow
    &lt;/h2&gt;
    &lt;div class="ltag__user__summary"&gt;
      &lt;a href="/marscode" class="ltag__user__link"&gt;
        MarsCode provides an AI-powered  IDE and an AI extension to assist your programming tasks.
      &lt;/a&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;



</description>
    </item>
    <item>
      <title>User Story EP3: How to Practice LeetCode Problems</title>
      <dc:creator>Dawn Zhao</dc:creator>
      <pubDate>Fri, 14 Jun 2024 05:12:21 +0000</pubDate>
      <link>https://forem.com/marscode/user-story-ep3-how-to-practice-leetcode-problems-5elj</link>
      <guid>https://forem.com/marscode/user-story-ep3-how-to-practice-leetcode-problems-5elj</guid>
      <description>&lt;p&gt;&lt;a href="https://leetcode.cn/?utm_source=LCUS&amp;amp;utm_medium=ip_redirect&amp;amp;utm_campaign=transfer2china" rel="noopener noreferrer"&gt;LeetCode&lt;/a&gt; is an online platform for coding interview preparation. The service provides coding and algorithmic problems intended for users to practice coding. LeetCode has gained popularity among job seekers and coding enthusiasts as a resource for technical interviews and coding competitions.&lt;/p&gt;

&lt;p&gt;In the past, when using LeetCode, I preferred to write down my problem-solving thoughts using a txt editor or plain paper, and then code using VS Code. When I encountered problems that I couldn't understand, I needed to consult Google or ChatGPT. Although this method helped to clarify my thoughts, solving a single problem required frequent switching between multiple tools. This not only consumed a lot of time but also interrupted the continuity of my thinking, resulting in low overall efficiency. Therefore, I have been looking for a solution that could simplify this process and improve my practice efficiency.&lt;/p&gt;

&lt;p&gt;Recently, a friend recommended an AI-powered Cloud IDE product called &lt;strong&gt;MarsCode&lt;/strong&gt; to me. The overall experience is quite similar to VS Code, while also providing a ready-to-use development environment that supports debugging and running. The best part is that the built-in AI assistant can provide more accurate answers by fully understanding the context. Next, I will share my experience of using MarsCode.&lt;/p&gt;

&lt;h2&gt;
  
  
  Preparation
&lt;/h2&gt;

&lt;p&gt;You need an account for MarsCode, which is very easy to get. Visit the MarsCode official website at &lt;a href="https://www.marscode.com/?utm_source=devto&amp;amp;utm_medium=post&amp;amp;utm_campaign=ep3" rel="noopener noreferrer"&gt;MarsCode&lt;/a&gt;, and then register (or log in) to your account. &lt;/p&gt;

&lt;p&gt;MarsCode offers various development templates, allowing users to start coding without worrying about setting up the programming environment. For instance, I chose Node.js here.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FuirQKCz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FuirQKCz.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;After creating, you can code just like you do with a local IDE.⬆️&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FVmJTnz6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FVmJTnz6.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;You can run the index.js by clicking the 'Run' button or executing node index.js in the terminal.⬆️&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Experience with MarsCode
&lt;/h2&gt;

&lt;p&gt;Usually, when I encounter a problem, I first jot down my thoughts on scratch paper. This time, to test MarsCode's capabilities, I jumped directly into the coding phase. Let's take a look at a classic LeetCode problem: the "&lt;a href="https://leetcode.com/problems/longest-palindromic-substring/description/" rel="noopener noreferrer"&gt;Longest Palindromic Substring&lt;/a&gt;"!&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FNjRj0Fs.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FNjRj0Fs.png"&gt;&lt;/a&gt;&lt;br&gt;
For LeetCode problems, we can write code with the assistance of MarsCode, or we can directly copy the LeetCode answer into the IDE and use AI capabilities to help us understand the problem and solution. MarsCode's AI assistant is very powerful, supporting features like code generation and code explanation. MarsCode can help me learn LeetCode in several key ways.&lt;/p&gt;

&lt;h2&gt;
  
  
  Coding
&lt;/h2&gt;

&lt;p&gt;When writing code, MarsCode provides three ways to assist with coding:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;While coding in the editor, the AI assistant infers your intentions based on the project context and comments, auto completing your code.&lt;/li&gt;
&lt;li&gt;Generate code directly in the editor through the Inline AI Chat.&lt;/li&gt;
&lt;li&gt;Chat with the AI assistant in the Side chat bar to get the AI to directly output the code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example, in the Node.js project created in the previous section, we can invoke &lt;strong&gt;Inline AI Chat&lt;/strong&gt; in index.js.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F7JYjHAw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F7JYjHAw.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2c2cWxybWJ0dWNoN29nMHM5bXZpeXRrdGYydW5pNXExY3c5bW1rZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/clq0zrSPbg9kpIBP5j/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExY2c2cWxybWJ0dWNoN29nMHM5bXZpeXRrdGYydW5pNXExY3c5bW1rZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/clq0zrSPbg9kpIBP5j/giphy.gif"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;When we input the problem, the AI assistant will infer the implementation of the function, even including the function call code!⬆️&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjhhcnQ3eDlzYWM4dHN0cGgwZnhhNm9zNGY3aHQ3ZjYzd2E1c2RoaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fnAXs655UwZ9DSLtuu/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjhhcnQ3eDlzYWM4dHN0cGgwZnhhNm9zNGY3aHQ3ZjYzd2E1c2RoaCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/fnAXs655UwZ9DSLtuu/giphy.gif"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;After accepting the code, click the Run button to test the code and see the results.⬆️&lt;/em&gt;&lt;br&gt;
&lt;a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDVjNGx3amlub2Vuc3JsNzd2bGV2cXJ6ZHRxZWJuZ3ZraWlsdnBlMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/TejrN6LPZA6ypsiRdC/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExZDVjNGx3amlub2Vuc3JsNzd2bGV2cXJ6ZHRxZWJuZ3ZraWlsdnBlMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/TejrN6LPZA6ypsiRdC/giphy.gif"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;If there are parts we don't understand, we can ask the AI assistant to explain them.⬆️&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Writing test cases
&lt;/h2&gt;

&lt;p&gt;Even though MarsCode has excellent coding capabilities, whether the code is completed by AI or by ourselves, we can use test cases to verify the correctness of the code.&lt;/p&gt;

&lt;p&gt;In fact, with the help of AI, our test cases can be more comprehensive. Taking the "Longest Palindromic Substring" as an example, we can use the AI assistant to generate test cases using Mocha. &lt;br&gt;
&lt;a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExYXBybzM3N3o1bmY3c3Y5d2QyeWNodjVwcmk1MTU3YXFkd25zMWVtOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2z6q7A2KKlN8G0GV8c/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExYXBybzM3N3o1bmY3c3Y5d2QyeWNodjVwcmk1MTU3YXFkd25zMWVtOCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/2z6q7A2KKlN8G0GV8c/giphy.gif"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;This way, we can easily and quickly verify accuracy through the test cases.⬆️&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Debug
&lt;/h2&gt;

&lt;p&gt;MarsCode provides templates that already support debugging capabilities. If there are any doubts about the code execution process, we can also use the Debug feature to understand the code execution step by step.&lt;br&gt;
&lt;a href="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExZXNwaGFrZzFzMHMzdjRncTV0Z2Z5MzQzZHpnOWc0NWU2b2xubmF4aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/UBhbHT9nzXJCLq6gUu/giphy.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://i.giphy.com/media/v1.Y2lkPTc5MGI3NjExZXNwaGFrZzFzMHMzdjRncTV0Z2Z5MzQzZHpnOWc0NWU2b2xubmF4aSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/UBhbHT9nzXJCLq6gUu/giphy.gif"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;Open the Debug panel on the right side and click the "Start Debugging" button.⬆️&lt;/em&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Exploring Better Solutions with AI
&lt;/h2&gt;

&lt;p&gt;We can explore more solutions by conversing with MarsCode's AI assistant. For example, in the previous example, we used the &lt;strong&gt;center expansion algorithm&lt;/strong&gt; for the longest palindromic substring, but another common solution is &lt;strong&gt;dynamic programming&lt;/strong&gt;.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FRM8ypmm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FRM8ypmm.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F1CXcmRz.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2F1CXcmRz.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;If we are not familiar with dynamic programming, we can ask further: What is dynamic programming?⬆️&lt;/em&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FucrvwQR.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fi.imgur.com%2FucrvwQR.png"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;We can also ask the AI assistant to provide some examples of dynamic programming. ⬆️&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;As you can see, on MarsCode, the AI assistant acts like a teammate, helping us gradually increase our understanding of the problem through conversation.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Overall, my experience with MarsCode has been excellent. Features like hassle-free setup, free AI, and resource environments are very helpful for validating ideas and boosting efficiency. However, when practicing LeetCode, your own thought process is paramount. I recommend first organizing your ideas and then using MarsCode to solve the problems. This approach maintains the flow of thought while leveraging the powerful tools MarsCode offers, ensuring you effectively and solidly grasp algorithms and coding techniques.&lt;/p&gt;

&lt;p&gt;Wishing you great success in your LeetCode practice!🎉        &lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
