Created
July 16, 2022 17:51
-
-
Save RingoMar/5bbf55f326a329f950ad59ca2c2792b8 to your computer and use it in GitHub Desktop.
Using json as a database with golang // Might be a better implementation / package but I would rather something local
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package database | |
import ( | |
"encoding/json" | |
"io/ioutil" | |
"log" | |
"os" | |
"time" | |
) | |
type HTMLMeta struct { | |
M_id string `json:"m_id"` | |
Time_ string `json:"time_"` | |
Uri string `json:"uri"` | |
Title string `json:"title"` | |
SiteName string `json:"site_name"` | |
Description string `json:"description"` | |
Image string `json:"image"` | |
Dname string `json:"dname"` | |
Message string `json:"message"` | |
} | |
type LinkersJson struct { | |
Database []HTMLMeta `json:"database"` | |
Lastupdated int32 `json:"lastupdated"` | |
} | |
func ReadJson(fileName string) []byte { | |
jsonFile, err := os.Open(fileName) | |
if err != nil { | |
log.Println("Creating file...") | |
linksJson := map[string]interface{}{ | |
"database": []map[string]string{}, | |
"lastupdated": int32(time.Now().Unix()), | |
} | |
data, _ := json.Marshal(linksJson) | |
f, err := os.OpenFile(fileName, | |
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) | |
if err != nil { | |
log.Println(err) | |
} | |
defer f.Close() | |
if _, err := f.WriteString(string(data) + "\n"); err != nil { | |
log.Println(err) | |
} | |
} | |
log.Println("Opening Database") | |
defer jsonFile.Close() | |
byteValue, _ := ioutil.ReadAll(jsonFile) | |
return byteValue | |
} | |
func WriteJSON(fileName string, data LinkersJson) { | |
jsonData, _ := json.MarshalIndent(data, "", " ") | |
ioutil.WriteFile(fileName, jsonData, os.ModePerm) | |
log.Println("Writing data to file...") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"time" | |
"localpack/loaction/database" | |
) | |
func main() { | |
databaseFile := database.ReadJson("linkers.json") | |
var jsonicData database.LinkersJson | |
json.Unmarshal(databaseFile, &jsonicData) | |
data := database.HTMLMeta{ | |
M_id: "test", | |
Time_: "test", | |
Uri: "test", | |
Title: "test", | |
SiteName: "test", | |
Description: "test", | |
Image: "test", | |
Dname: "test", | |
Message: "test", | |
} | |
jsonicData.Lastupdated = int32(time.Now().Unix()) | |
jsonicData.Database = append(jsonicData.Database, data) | |
database.WriteJSON("linkers.json", jsonicData) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment