Go is an open-source programing language developed by Google developers and other contributors. With google’s exceptional action, golang has provided extreme help in the business of various applications. Go language ensures code efficiency that transposes into faster software and applications for enterprises. Golang 2021 has lots of opportunities for developers and golang best practices will help you in quick and effective development in 2021 and can contribute to a vast extent in shaping software techniques and strategies with delivery in the future. Here you will get to know the details of best practices of golang that enhance the code quality.
Also know the reasons to use go for nativemobile app development at- Why You Should Go For Native Mobile App Development?
Golang Best Practices To Follow In 2021-

1. Don’t Repeat Till It Is Necessary-
Creating a common file to store structure and later use those saved structures for controllers and models is really a great thought. Just ensure to follow Go project structure best practices.
Get it from the below example-
type binWriter struct {
w io.Writer
Size int64
err error
}
//Write writes a value to provided writer in small endian form.
func (w *binWriter) Write(v interface{}) {
if w.err != nil {
return
}
if w.err = binary.Writer(w.w, binary.LittleEndian, v); w.err == nil {
W.size += int64(binary.Size(v))
}
}
Here you can avoid repetition by using binWriter,
func (g *Gopher) WriteTo(w io.Writer) (int64, error) {
bw := &binWriter{w: w}
bw.Write(int32(len(g.Name)))
bw.Write([]byte(g.Name))
bw.Write(int64(g.AgeYears))
Return bw.size, bw.err
}
2. Give Priority To Necessary Code-
If you have important information such as build tags, license information, package documentation, then initially describe it. You can divide the Import statements related groups. The standard library packages exist in the first group.
import (
“ fmt”
“io”
“log”
“golang.org/x/net/websocket”
)
The remaining code begins with the important types and ends with helper function and types.
3. Managing Multiple Files In The Same package-
Should you break a particular package into various files?
- Prevent long files
Standard library’s net/http package includes 15734 lines in 47 files.
- Divide code and tests
net/http/cookie.go and net/http/cookie_test.go are parts of http package.
Ideally, test code is compiled on at test time.
Divided package documentation
When a package has more than one file, it is an agreement to create a doc.go compromising the package documentation.
4. Say No To Concurrency In APIs-
func doConcurrently(job string, err chan error) {
go func() {
fmt.Println(“doing job”, job)
time.Sleep(1 * time.Second)
err <- errors.New(“something went wrong!”)
}()
}
func main() {
jobs := [ ]string{“one”, “two”, “three”}
errc := make(chan error)
for _, job := range jobs {
doConcurrently(job, errc)
}
for _= range jobs {
if err := <-errc; err !=nil {
fmt.Println(err)
}
}
}
If needed, how to use it sequentially?
func do(job string) err {
fmt.Println(“doing job”, job)
time.Sleep(1 * time.Second)
return errors.new(“something went wrong!”)
}
func main() {
Jobs := [ ]string{“one”, “two”, “three”}
errc := make(chan error)
for _, job := range jobs {
go func(job string) {
errc <- do(job)
}(job)
for _= range jobs {
if err := <-errc; err != nil {
fmt.Println(err)
}
}
}
Reveal synchronous APIs as calling them simultaneously is easy and reliable.
5. Avoid Goroutine Leaks-
func sendMsg(msg, addr string) error {
conn, err := net.Dial(“tcp”, addr)
if err != nil {
return err
}
defer conn.Close()
_, err = fmt.Fprint(conn, msg)
return err
}
func main() {
addr := [ ]string{“localhost:808”, “http:google.com”}
err := broadcastMsg(“hi”, addr)
time.Sleep(time.Second)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(“something went fine”)
}
func broadcastMsg(msg string, addrs [ ]string) error {
errc :=make(chan error)
for _, addr := range addrs {
go func(addr string){
errc <- sendMsg(msg, addr)
fmt.Println(“done”)
}(addr)
}
for _= range addrs {
if err := <-errc; err != nil {
return err
}
}
return nil
}
- Goroutine carries a source to the chan
- The goroutine is blocked on chan write
- chan will never be accumulated with garbage
func broadcastMsg(msg string, addrs [ ]string) error {
errc := make(chan error, len(addrs))
for _, addr := range address {
go func(addr string) {
errc <- sendMsg(msg, addr)
fmt.Println(“done”)
}(addr)
}
for _= range addrs {
if err := <-errc; err !=nil {
return err
} }
return nil
}
If the capacity of the channel stays unpredicted, what to do?
func broadcastMsg(msg string, addrs [ ]string) error {
errc := make(chan error)
quit := make(chan struct{})
defer close(quit)
for _, addr := range address {
go func(addr string) {
select {
case errc <- sendMsg(msg, addr):
fmt.Println(“done”)
case <-quit :
fmt.Println(“quit”)
} }(addr)
}
No comments:
Post a Comment