Programming Go (WIP)

Rodrigo Ancavil
Aug 12, 2023

--

This is a set of snippets with go code.

JSON

package main

import (
"bufio"
"encoding/json"
"io"
"fmt"
"os"
)

type User struct {
Id int
Username string
}

func check(e error) {
if e != nil {
panic(e)
}
}

func main() {
user := User{1,"fred"}

fmt.Println("Using Encoder to write json directly to Standard Output")

enc := json.NewEncoder(os.Stdout)
err := enc.Encode(user)
check(err)

fmt.Println("Using Encoder to write json directly to File user.json")

f, err := os.Create("./user.json")
check(err)

fd := bufio.NewWriter(f)
enc = json.NewEncoder(fd)
enc.Encode(user)
fd.Flush()

var user_from_file User
f, err = os.Open("./user.json")
check(err)
dec := json.NewDecoder(f)

for err := dec.Decode(&user_from_file); err != nil && err != io.EOF; {
panic(err)
}
fmt.Println(user_from_file.Id, user_from_file.Username)
f.Close()
}

--

--

Rodrigo Ancavil
Rodrigo Ancavil

Written by Rodrigo Ancavil

IT Architect and Software Engineer

No responses yet