package main
import (
"fmt"
"log"
"os"
"sync"
"strings"
"io/ioutil"
"encoding/json"
)
type demo struct {
}
type creStruct struct {
Name string `json:"name"`
Ak string `json:"ak"`
Sk string `json:"sk"`
}
type cre struct {
Cres []creStruct `json:"credentials"`
}
func Newdemo() *demo {
dem := &demo{}
return dem
}
var wg sync.WaitGroup
func (d *demo) LoadCredentials(path string) cre{
jsonFile, err := os.Open(path)
if err != nil {
log.Println(err)
}
defer jsonFile.Close()
byteValue, err := ioutil.ReadAll(jsonFile)
if err != nil {
log.Println(err)
}
var cres cre
err = json.Unmarshal(byteValue, &cres)
if err != nil {
log.Println(err)
}
data, err := json.MarshalIndent(cres, "", " ")
if err != nil {
log.Println(err)
}
fmt.Printf("%s\n", data)
return cres
}
func (d *demo) PrintCredential(cres cre) {
wg.Add(len(cres.Cres))
for _, i := range cres.Cres {
go func(email, ak, sk string) {
defer wg.Done()
name := strings.Split(email, "@")
fmt.Printf("name: %s, ak: %s, sk: %s\n", name[0], ak, sk)
}(i.Name, i.Ak, i.Sk)
}
}
func init() {
f, err := os.OpenFile("goerror.log", os.O_APPEND | os.O_CREATE | os.O_RDWR, 0666)
if err != nil {
log.Fatal(err)
}
log.SetPrefix("Trace: ")
log.SetOutput(f)
}
func main() {
mydemo := Newdemo()
val := mydemo.LoadCredentials("/root/goProj/credential.json")
mydemo.PrintCredential(val)
wg.Wait()
}
{
"credentials": [
{
"name": "********@.onaliyun.com",
"ak": "********",
"sk": "********"
},
{
"name": "********@.onaliyun.com",
"ak": "********",
"sk": "********"
}
]
}
- Use WaitGroup.Add(int) to keep count of how many goroutines we will be running as part of our logic.
- Use WaitGroup.Done() to signal that a goroutine is done with its task.
- Use WaitGroup.Wait() to wait until all goroutines are done.
- Pass WaitGroup instance to the goroutines so they can call the Done() method.