Example of Go Language Programming (6)

Posted by ForumSecure on Mon, 03 Jun 2019 00:30:27 +0200

This section mainly shares: JSON, Time and Date, Epoch, Time Format Resolution, Pseudo-Random Numbers

Go JSON instance

JSON format is frequently used in network communication, simple and elegant. Go provides built-in support for JSON encoding and decoding, including built-in and custom data types.

package main

import (
    "encoding/json"
    "fmt"

    "os"
)

type Response1 struct{
    Page int
    Fruits []string
}

type Response2 struct{
    Page   int       `json:"page"`
    Fruits []string  `json:"fruits"`
}

func main(){
    bolB,_:=json.Marshal(true)
    fmt.Println(string(bolB))

    intB,_:=json.Marshal(1)
    fmt.Println(string(intB))

    fltB,_:=json.Marshal(2.34)
    fmt.Println(string(fltB))

    //slice, map example encoded into json array

    slcD := []string{"apple","peach","pear"}
    slcB , _ := json.Marshal(slcD)
    fmt.Println(string(slcB))

    mapD := map[string]int {"apple":5,"lettuce":7}
    mapB , _ := json.Marshal(mapD)
    fmt.Println(string(mapB))


    //Autocoding Custom Data
    res1D := &Response1{
        Page: 1,
        Fruits:[]string{"apple","peach","pear"}}
    res1B ,_ :=json.Marshal(res1D)
    fmt.Println(string(res1B))

    res2D := &Response2{
        Page: 1,
        Fruits:[]string{"apple","peach","pear"}}
    res2B , _ := json.Marshal(res2D)
    fmt.Println(string(res2B))

    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)

    var dat map[string]interface{}

    if err := json.Unmarshal(byt,&dat);err != nil{
        panic(err)
    }
    fmt.Println(dat)

    num:= dat["num"].(float64)
    fmt.Println(num)

    strs := dat["strs"].([]interface{})
    str1 := strs[0].(string)
    fmt.Println(str1)

    str := `{"page":1,"fruits":["apple","peach"]}`
    res := Response2{}

    json.Unmarshal([]byte(str),&res)
    fmt.Println(res)
    fmt.Println(res.Fruits[0])

    enc:= json.NewEncoder(os.Stdout)
    d := map[string]int{"apple":5,"lettuce":7}
    enc.Encode(d)
}

Go Time and Date Programming

Go programming provides extensive support for time and duration. Examples start with the acquisition of the current time, create a time structure for parsing, time comparison, the problem of the interval between two times, the problem of time addition and subtraction.

package main

import (
    "fmt"
    "time"
)

func main(){
    p := fmt.Println

    //Get the current time
    nowtime := time.Now()
    p(nowtime)

    //Create a time structure for parsing
    then := time.Date(
        2017,8,18,19,34,52,621544,time.UTC)

    p(then)

    //There are different examples of other functions that can be used here.
    p(then.Year())
    p(then.Month())
    p(then.Second())
    p(then.Location())
    p(then.Weekday())

    //At the same time, time comparison can be made.
    p(then.Before(nowtime))
    p(then.After(nowtime))
    p(then.Equal(nowtime))

    //The interval between two times
    diff := nowtime.Sub(then)

    p(diff)

    p(diff.Hours())
    p(diff.Minutes())
    p(diff.Seconds())
    p(diff.Nanoseconds())

    //Time addition and subtraction
    p(then.Add(diff))
    p(then.Add(-diff))
}

Examples of the Go Age (Epoch)

A common requirement in programs is to get the number of seconds, milliseconds, or nanoseconds depending on Unix epochs. Examples are time.Now using Unix or UnixNano to obtain time elapsed since the Unix era in seconds or nanoseconds, respectively.

There are also ways to convert integer seconds or nanoseconds to the corresponding time.

package main

import (
    "time"
    "fmt"
)

func main(){

    //Use time.Now() with Unix or UnixNano to get time
    now  := time.Now()
    secs := now.Unix()
    nanos:= now.UnixNano()
    fmt.Println(now)


    millis := nanos/1000000
    fmt.Println(secs)
    fmt.Println(millis)
    fmt.Println(nanos)

    //Solving backwards in seconds or nanoseconds

    fmt.Println(time.Unix(secs,0))
    fmt.Println(time.Unix(0,nanos))
}

Go Time Formatting/Parsing Example

Go supports time formatting and parsing through pattern-based layouts. Here is a basic example of formatting time based on RFC3339, as well as error examples.

package main

import (
    "fmt"
    "time"
)

func main(){
    p := fmt.Println

    t := time.Now()
    p(t.Format(time.RFC3339))


    t1 , _ := time.Parse(
        time.RFC3339,
        "2017-11-01T22:35:52+00:00")
    p(t1)

    //Formatting and parsing

    p(t.Format("3:04PM"))
    p(t.Format("Mon Jan _2 15:04:05 20017"))
    p(t.Format("2006-01-02T15:04:05.99999-08:00"))

    form := "3 04 PM"
    t2,_ := time.Parse(form,"8 41 PM")
    p(t2)

    fmt.Printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
            t.Year(),t.Month(),t.Day(),
            t.Hour(),t.Minute(),t.Second())

    //error handling
    ansic := "Mon jan _2 15:04:05 2006"
    _,e:=time.Parse(ansic,"8:41PM")
    p(e)
}

Go Random Number Example

The math/rand package of Go provides pseudo-random number generation. For example, rand.Intn returns a random int n, 0 <= n < 100. rand.Float64 returns a float64 f, 0.0 <= f < 1.0. This can be used to produce random floating points in other ranges, such as 5.0 <= f < 10.0

This is a pseudo-random number. The first random number produced by each call function is the same.

package main

import (
    "fmt"
    "math/rand"
)

func main(){
    p := fmt.Println

    //Generating Pseudo-Random Numbers of 0-100
    p(rand.Intn(100))
    p(rand.Intn(100))

    //Generating floating-point random numbers
    p(rand.Float64())
    p(rand.ExpFloat64()*10)
    p(rand.ExpFloat64()*100)

    
}

For further discussion, we can add group: 295023494

Topics: JSON Unix encoding Programming