Update tech_docs/go_getting_started.md

This commit is contained in:
2024-06-18 05:07:05 +00:00
parent 8ef9f4fe62
commit 42bc9e1f96

View File

@@ -1,3 +1,326 @@
Go offers robust support for working with various data formats like CSV, JSON, and databases. Heres a detailed overview of what Go provides for each:
### CSV
#### Standard Library: `encoding/csv`
The `encoding/csv` package is part of the Go standard library and is used for reading and writing CSV files.
**Reading CSV Files:**
```go
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
file, err := os.Open("data.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
reader := csv.NewReader(file)
records, err := reader.ReadAll()
if err != nil {
fmt.Println("Error:", err)
return
}
for _, record := range records {
fmt.Println(record)
}
}
```
**Writing CSV Files:**
```go
package main
import (
"encoding/csv"
"os"
)
func main() {
file, err := os.Create("output.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
data := [][]string{
{"Name", "Age", "City"},
{"Alice", "30", "New York"},
{"Bob", "25", "San Francisco"},
}
for _, record := range data {
if err := writer.Write(record); err != nil {
fmt.Println("Error:", err)
return
}
}
}
```
### JSON
#### Standard Library: `encoding/json`
The `encoding/json` package provides functionalities to encode and decode JSON data.
**Reading JSON Files:**
```go
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
file, err := os.Open("data.json")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
byteValue, _ := ioutil.ReadAll(file)
var people []Person
json.Unmarshal(byteValue, &people)
for _, person := range people {
fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
}
}
```
**Writing JSON Files:**
```go
package main
import (
"encoding/json"
"fmt"
"os"
)
type Person struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
}
file, err := os.Create("output.json")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
encoder := json.NewEncoder(file)
if err := encoder.Encode(people); err != nil {
fmt.Println("Error encoding JSON:", err)
}
}
```
### Databases
#### SQL Databases
Go provides excellent support for SQL databases via the `database/sql` package and various drivers for specific databases like MySQL, PostgreSQL, and SQLite.
**Connecting to a MySQL Database:**
```go
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/dbname")
if err != nil {
fmt.Println("Error connecting to database:", err)
return
}
defer db.Close()
rows, err := db.Query("SELECT id, name FROM users")
if err != nil {
fmt.Println("Error querying database:", err)
return
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err := rows.Scan(&id, &name)
if err != nil {
fmt.Println("Error scanning row:", err)
return
}
fmt.Printf("ID: %d, Name: %s\n", id, name)
}
}
```
#### NoSQL Databases
Go also supports NoSQL databases like MongoDB through third-party packages.
**Connecting to a MongoDB Database:**
```go
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"time"
)
func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
fmt.Println("Error creating MongoDB client:", err)
return
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
fmt.Println("Error connecting to MongoDB:", err)
return
}
defer client.Disconnect(ctx)
collection := client.Database("testdb").Collection("testcollection")
filter := bson.D{{"name", "Alice"}}
var result bson.M
err = collection.FindOne(ctx, filter).Decode(&result)
if err != nil {
fmt.Println("Error finding document:", err)
return
}
fmt.Printf("Found document: %+v\n", result)
}
```
### Working with YAML
#### Third-Party Library: `go-yaml/yaml`
**Reading YAML Files:**
```go
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
)
type Config struct {
Version string `yaml:"version"`
AppName string `yaml:"app_name"`
}
func main() {
file, err := os.Open("config.yaml")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
byteValue, _ := ioutil.ReadAll(file)
var config Config
yaml.Unmarshal(byteValue, &config)
fmt.Printf("Version: %s, AppName: %s\n", config.Version, config.AppName)
}
```
**Writing YAML Files:**
```go
package main
import (
"fmt"
"gopkg.in/yaml.v2"
"os"
)
type Config struct {
Version string `yaml:"version"`
AppName string `yaml:"app_name"`
}
func main() {
config := Config{
Version: "1.0",
AppName: "MyApp",
}
file, err := os.Create("output.yaml")
if err != nil {
fmt.Println("Error creating file:", err)
return
}
defer file.Close()
data, err := yaml.Marshal(&config)
if err != nil {
fmt.Println("Error marshaling YAML:", err)
return
}
file.Write(data)
}
```
### Summary
Go provides strong support for working with various data formats and databases:
- **CSV**: `encoding/csv` for reading and writing CSV files.
- **JSON**: `encoding/json` for encoding and decoding JSON data.
- **SQL Databases**: `database/sql` package with drivers for MySQL, PostgreSQL, SQLite, etc.
- **NoSQL Databases**: Libraries like `mongo-go-driver` for MongoDB.
- **YAML**: `go-yaml/yaml` for encoding and decoding YAML data.
These packages and libraries enable Go developers to efficiently manage and manipulate data across different formats and storage systems.
---
Go provides strong support for working with various file formats such as CSV, JSON, Markdown, and YAML. Let's dive into the specifics for each of these formats.
### CSV