Posts

Showing posts with the label golang

byte, int, rune in Golang

byte <=> uint8  rune <=> int32

Go wire

 https://blog.drewolson.org/go-dependency-injection-with-wire

What is the difference between 2 code blocks

package main import ( "fmt" "github.com/sirupsen/logrus" "runtime/debug" "time" ) func main () { defer func () { if err := recover (); err != nil { logrus . Errorln ( "main" , err ) debug . PrintStack () } }() GoInside ( nil ) time . Sleep ( 2 * time . Second ) fmt . Println ( "After panic" ) } type Test struct { X int } func GoInside ( v * Test ) { go NullPointer ( v . X ) } func NullPointer ( X int ) { fmt . Println ( X ) } This above code can handle a panic error , but the code below can not handle a panic ==> why  package main import ( "fmt" "github.com/sirupsen/logrus" "runtime/debug" "time" ) func main () { defer func () { if err := recover (); err != nil { logrus . Errorln ( "main" , err ) debug . PrintStack () } }() GoInside () time . Sleep ( 2 * ti...

How to handle panic error in Golang

ref:  https://ednsquare.com/story/learn-go-panic-and-recover-in-golang------1HSVNg func main () { NullPointer ( nil ) time . Sleep ( 2 * time . Second ) fmt . Println ( "After panic" ) } type Test struct { X int } func NullPointer ( v * Test ) { fmt . Println ( v . X ) } Đoạn code trên dễ dàng gây ra lỗi panic và stop hàm main panic: runtime error: invalid memory address or nil pointer dereference Vậy chúng ta cần làm gì để tránh gây chết hàm main đây Nếu là java hoặc ngôn ngữ khác thì chúng ta đã có try catch finally  Còn trong golang bạn sẽ có một cách trông đẹp mắt hơn func main () { defer func () { if err := recover (); err != nil { logrus . Errorln ( err ) debug . PrintStack () } }() NullPointer ( nil ) time . Sleep ( 2 * time . Second ) fmt . Println ( "After panic" ) } type Test struct { X int } func NullPointer ( v * Test ) { fmt . Println ( v . X ) } Theo cách này thì trong hàm main chúng ta ...

Careful when comparing value with nil in Golang

func main () { err := Foo () fmt . Println ( err == nil ) } func Foo () error { var err * os . PathError = nil return err } /tmp/___go_build_main_go #gosetup false Process finished with exit code 0 Best practice func main () { err := Foo () fmt . Println ( err == nil ) } func Foo () error { var err * os . PathError = nil if err != nil { return errors . New ( "Not nil" ) } return nil } /tmp/___go_build_main_go #gosetup true Process finished with exit code 0

getLongest

func main () { fmt . Print ( getLongest ( "111131111" )) } func getLongest ( input string ) string { arr := make ([][] bool , len ( input )) for i := range arr { arr [ i ] = make ([] bool , len ( input )) } r := input [ 0 : 1 ] for i := 0 ; i < len ( input ); i ++ { arr [ i ][ i ] = true if i != len ( input )- 1 && input [ i ] == input [ i + 1 ] { r = input [ i : i + 1 ] arr [ i ][ i + 1 ] = true } } for lenght := 3 ; lenght <= len ( input ); lenght ++ { for i := 0 ; i < len ( input ); i ++ { j := i + lenght - 1 if j < len ( input ) && isPar ( i , j , input , arr ) { arr [ i ][ j ] = true r = input [ i : j + 1 ] } } } return r } func isPar ( i , j int , s string , arr [][] bool ) bool { if i == j { arr [ i ][ j ] = true return true } else { if i + 1 == j && s [ i ] == s [ j ]...

read file in golang

pwd , _ := os . Getwd () jsonFile , err := ioutil . ReadFile ( pwd + "/fakeFundDataJson.json" ) if err != nil { fmt . Println ( err ) } fmt . Println ( "Successfully Opened users.json" ) w . Write ( jsonFile ) w . WriteHeader ( http . StatusOK ) w . Header (). Add ( "Content-type" , "application/json" )

Json tag in golang

type Dummy struct { Name string `json:"name,omitempty"` Number int64 `json:"number,omitempty"` Pointer * string `json:"pointer,omitempty"` xxx string `json:"-"` // ignore this field yyy string `json:"-,"` // print this field with named - }

How to set Isolation Level for each transaction in Golang

psqlInfo := fmt . Sprintf ( "host=%s port=%d user=%s " + "password=%s dbname=%s sslmode=disable" , host , port , user , password , dbname ) db , err := sqlx . Open ( "postgres" , psqlInfo ) // create a TX tx , err := db . BeginTxx ( context , & sql . TxOptions { Isolation : sql . LevelDefault }) rows , err := tx . Query ( `select amount from person where id=$1` , 1 ) .... Belows is some types of level in Golang support // IsolationLevel is the transaction isolation level used in TxOptions. type IsolationLevel int // Various isolation levels that drivers may support in BeginTx. // If a driver does not support a given isolation level an error may be returned. // // See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels. const ( LevelDefault IsolationLevel = iota LevelReadUncommitted LevelReadCommitted LevelWriteCommitted LevelRepeatableRead LevelSnapshot LevelSerializable LevelLi...

Transaction Isolation

Image
Ref: https://www.postgresql.org/docs/9.5/transaction-iso.html The SQL standard defines four levels of transaction isolation. The most strict is Serializable, which is defined by the standard in a paragraph which says that any concurrent execution of a set of Serializable transactions is guaranteed to produce the same effect as running them one at a time in some order. The other three levels are defined in terms of phenomena, resulting from interaction between concurrent transactions, which must not occur at each level. The standard notes that due to the definition of Serializable, none of these phenomena are possible at that level. (This is hardly surprising -- if the effect of the transactions must be consistent with having been run one at a time, how could you see any phenomena caused by interactions?) The phenomena which are prohibited at various levels are: dirty read A transaction reads data written by a concurrent uncommitted transaction. nonrepeatable read A transact...

Dockerfile tutorial

FROM golang:latest Lệnh này là khai báo base image được dùng để tạo new image. golang: tên base image latest: version của base image, bạn cũng có thể dùng sha256 để xác định rõ một version golang@sha256 RUN mkdir /app câu lệnh này dùng để thực thi một câu lệnh cmd trên new image, tương tư như câu lệnh trên terminal thông thường Tạo một layer trong new image Câu lệnh này đượng thực thi trong vòng đời "build time" nghĩa là build new image ADD      .       /app/ Lệnh này dùng để copy thư mục hiện tại (.)  vào thư mục app trên new image WORKDIR /app câu lệnh này tương tự như câu lệnh cd trong terminal, ý là chỉ con trỏ tới thư mục working /app RUN go build -o main .  Lệnh này tương tự như bạn chạy câu lệnh trong terminal là "go build -o main" CMD ["/app/main"] lệnh này tương tự như lệnh RUN là chạy một câu lệnh nhưng nó cho phép bạn truyền thêm tham số Lệnh này là lệnh running time trong vòng đời. Nó chỉ thực thi khi ảnh đã...

Defer close(channel) - Golang tutorial

Always remind yourself closing your opened channel Like this example valueChannel := make( chan int ) defer close( valueChannel ) this ensures that you clean up your bedroom when you are leaving it

WaitGroup - Golang tutorial

https://tutorialedge.net/golang/go-waitgroup-tutorial/ When you have a long time job to run in your program But you need to wait for the result to printout it --> the best way is to use Waitgroup package main import ( "fmt" "sync" ) func myFunc (waitgroup *sync.WaitGroup) { fmt. Println ( "Inside my goroutine" ) waitgroup. Done () } func main () { fmt. Println ( "Hello World" ) var waitgroup sync.WaitGroup waitgroup. Add ( 1 ) go myFunc (&waitgroup) waitgroup. Wait () fmt. Println ( "Finished Execution" ) } You can use anonymous function package main import ( "fmt" "sync" ) func main () { fmt. Println ( "Hello World" ) var waitgroup sync.WaitGroup waitgroup. Add ( 1 ) go func () { fmt. Println ( "Inside my goroutine" ) waitgroup...