Cara Print Variabel Struct dan JSON di Golang
- Categories:
- golang
Salah satu cara debug saat membuat program adalah melakukan print atau menampilkan suatu variabel. Pada Golang, hal ini dapat dilakukan dengan dua cara, yaitu dengan Printf
dan json.Marshal
ditambah Println
.
package main
import (
"fmt"
"encoding/json"
)
type Project struct {
Id int `json:"project_id"`
Name string `json:"name"`
}
func main() {
myProject := Project{
Id: 1,
Name: "@kaklabs",
}
fmt.Printf("%+v\n", myProject)
yourProject := Project{
Id: 2,
Name: "KAK Labs",
}
res, _ := json.Marshal(yourProject)
fmt.Println(string(res))
}
Keluaran dari kode Go diatas adalah sebagai berikut.
{Id:1 Name:@kaklabs}
{"project_id":2,"name":"KAK Labs"}
Perbedaan dari kedua cara diatas adalah %+v
menampilkan field dari struct
sedangkan json.Marshal
menampilkan field dari JSON. Kode diatas dapat diakses melalui The Go Playground.
Recent Posts
AWS Secrets Manager
Explanation about AWS Secrets Manager with example code.
Envelope Encryption
Envelope encryption is the practice of encrypting plaintext data with a data key, and then encrypting the data key under another key.
Tutorial - "su username vs su - username" - A Security Perspective
The main difference between `su username` and `su - username` lies in the environment variables that are loaded when switching to the specified user.
Subdomain Hijacking
My dormant subdomain was recently hijacked, redirecting it to a online gamble registration page.
C# DbContext ServiceLifeTime
my note about C Sharp ServiceLifeTime