generated from ACM-VIT/hacktoberfest-readme
-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathdb.go
109 lines (90 loc) · 2.07 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
func IsExistDB() bool {
if _, err := os.Stat("db.json"); err == nil {
return true
} else {
return false
}
}
func CreateDB() bool {
os.Create("db.json")
return true
}
func WriteToDB(key, value string) bool {
if IsExistDB() {
jsonFile, err := os.Open("db.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
// Declared an empty map interface
result := make(map[string]interface{})
// Unmarshal or Decode the JSON to the interface.
json.Unmarshal(byteValue, &result)
result[key] = value
// Marshal or Encode the interface data
jsonResult, _ := json.Marshal(result)
// Write the JSON data to the file
ioutil.WriteFile("db.json", jsonResult, 0644)
return true
} else {
return false
}
}
func ReadFromDB(key string) (string, bool) {
if IsExistDB() {
jsonFile, err := os.Open("db.json")
if err != nil {
fmt.Println(err)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
// Declared an empty map interface
var result map[string]interface{}
// Unmarshal or Decode the JSON to the interface.
json.Unmarshal(byteValue, &result)
// Reading each value by its key
if result[key] != nil {
return result[key].(string), true
} else {
return "", false
}
} else {
return "", false
}
}
// func main() {
// fmt.Println("Enter the number:\n1. Check the DataBase\n2. Make a new DataBase\n3. Add data to the database\n4. Check wheather the data is exists or not in the DataBase")
// var mainCase int
// fmt.Scan(&mainCase);
// switch mainCase {
// case 1:
// fmt.Println(isExistDB())
// break
// case 2:
// fmt.Println(createDB())
// break
// case 3:
// fmt.Println("Enter Key and Value")
// var key string
// var value string
// fmt.Scanln(&key)
// fmt.Scanln(&value)
// fmt.Println(writeToDB(key, value))
// break
// case 4:
// var key string
// fmt.Scanln(&key)
// fmt.Println(readFromDB(key))
// break
// default:
// fmt.Errorf("No Number Pressed")
// }
// }