Skip to content

Instantly share code, notes, and snippets.

@Double1996
Last active August 28, 2019 03:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Double1996/677aca8b4ecf53e266f1be4f7528782a to your computer and use it in GitHub Desktop.
Save Double1996/677aca8b4ecf53e266f1be4f7528782a to your computer and use it in GitHub Desktop.
golang 各种操作数据库 #mongo #file
package main;
import (
"os"
"fmt"
"strconv"
)
func main() {
//打开文件,返回文件指针
file, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
fmt.Println(file);
file.Close();
//以读写方式打开文件,如果不存在,则创建
file2, error := os.OpenFile("./2.txt", os.O_RDWR|os.O_CREATE, 0766);
if error != nil {
fmt.Println(error);
}
fmt.Println(file2);
file2.Close();
//创建文件
//Create函数也是调用的OpenFile
file3, error := os.Create("./3.txt");
if error != nil {
fmt.Println(error);
}
fmt.Println(file3);
file3.Close();
//读取文件内容
file4, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
//创建byte的slice用于接收文件读取数据
buf := make([]byte, 1024);
//循环读取
for {
//Read函数会改变文件当前偏移量
len, _ := file4.Read(buf);
//读取字节数为0时跳出循环
if len == 0 {
break;
}
fmt.Println(string(buf));
}
file4.Close();
//读取文件内容
file5, error := os.Open("./1.txt");
if error != nil {
fmt.Println(error);
}
buf2 := make([]byte, 1024);
ix := 0;
for {
//ReadAt从指定的偏移量开始读取,不会改变文件偏移量
len, _ := file5.ReadAt(buf2, int64(ix));
ix = ix + len;
if len == 0 {
break;
}
fmt.Println(string(buf2));
}
file5.Close();
//写入文件
file6, error := os.Create("./4.txt");
if error != nil {
fmt.Println(error);
}
data := "我是数据\r\n";
for i := 0; i < 10; i++ {
//写入byte的slice数据
file6.Write([]byte(data));
//写入字符串
file6.WriteString(data);
}
file6.Close();
//写入文件
file7, error := os.Create("./5.txt");
if error != nil {
fmt.Println(error);
}
for i := 0; i < 10; i++ {
//按指定偏移量写入数据
ix := i * 64;
file7.WriteAt([]byte("我是数据"+strconv.Itoa(i)+"\r\n"), int64(ix));
}
file7.Close();
//删除文件
del := os.Remove("./1.txt");
if del != nil {
fmt.Println(del);
}
//删除指定path下的所有文件
delDir := os.RemoveAll("./dir");
if delDir != nil {
fmt.Println(delDir);
}
}
// grom 简单的用法
package main
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type Product struct {
gorm.Model
Code string
Price uint
}
func main() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&Product{})
// Create
db.Create(&Product{Code: "L1212", Price: 1000})
// Read
var product Product
db.First(&product, 1) // find product with id 1
db.First(&product, "code = ?", "L1212") // find product with code l1212
// Update - update product's price to 2000
db.Model(&product).Update("Price", 2000)
// Delete - delete product
db.Delete(&product)
}
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"time"
)
type Content struct {
Name string
Download int
Date time.Time
}
var (
Session, _ = mgo.Dial("localhost")
Database = "mgo"
Collection = "content"
Coll = Session.DB(Database).C(Collection)
content = &Content{
Name: "this-is-good-content",
Download: 1,
Date: time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
//Date: time.Now(),
}
)
//Drop Database
func dropDatabase() {
fmt.Println("Drop Database")
//db.dropDatabase()
err := Session.DB(Database).DropDatabase()
if err != nil {
panic(err)
}
}
//Insert
func testInsert() {
fmt.Println("Test Insert into MongoDB")
c := bson.M{
"name": "this-is-good-content",
"download": 1,
"date": time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
}
/*
db.content.insert({
Name: "this-is-good-content",
Download: 1,
Date: new Date("2016-04-07"),
}
)
*/
Coll.Insert(c)
}
//Multiple Insert
func testMultipleInsert() {
fmt.Println("Test Multiple Insert into MongoDB")
var contentArray []interface{}
/*
db.content.insert([
{
Name: "this-is-good-content",
Download: 1,
Date: new Date("2016-04-07"),
},
{
Name: "this-is-good-content",
Download: 2,
Date: new Date("2016-04-07"),
},
{
Name: "this-is-good-content",
Download: 3,
Date: new Date("2016-04-07"),
},
{
Name: "this-is-good-content",
Download: 4,
Date: new Date(),
},
]
)
*/
//contentArray = append(contentArray, &Content{
// Name: "this-is-good-content",
// Download: 1,
// Date: time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
//})
contentArray = append(contentArray, bson.M{
"name": "this-is-good-content",
"download": 1,
"date": time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
})
contentArray = append(contentArray, &Content{
Name: "this-is-good-content",
Download: 2,
Date: time.Date(2016, 4, 8, 0, 0, 0, 0, time.UTC),
})
//same date
contentArray = append(contentArray, &Content{
Name: "this-is-good-content",
Download: 3,
Date: time.Date(2016, 4, 8, 0, 0, 0, 0, time.UTC),
})
contentArray = append(contentArray, &Content{
Name: "this-is-good-content",
Download: 3,
Date: time.Date(2016, 4, 9, 0, 0, 0, 0, time.UTC),
})
contentArray = append(contentArray, &Content{
Name: "this-is-good-content2",
Download: 4,
Date: time.Now(),
})
Coll.Insert(contentArray...)
}
//Bulk Insert
func testBulkInsert() {
fmt.Println("Test Bulk Insert into MongoDB")
bulk := Coll.Bulk()
var contentArray []interface{}
contentArray = append(contentArray, &Content{
Name: "this-is-good-content",
Download: 1,
Date: time.Date(2016, 4, 7, 0, 0, 0, 0, time.UTC),
})
contentArray = append(contentArray, &Content{
Name: "this-is-good-content",
Download: 2,
Date: time.Now(),
})
bulk.Insert(contentArray...)
_, err := bulk.Run()
if err != nil {
panic(err)
}
}
//Update
//db.collection.update(
// <query>,
// <update>,
// {
// upsert: <boolean>,
// multi: <boolean>,
// writeConcern: <document>
// }
//)
func testUpdate() {
fmt.Println("Test Update in MongoDB")
//db.content.update({name: "this-is-good-content"})
selector := bson.M{"name": "this-is-good-content"}
//Update One and Replace Doc
//update := bson.M{"download": 3}
//err := Coll.Update(selector, update)
//Update One
//update := bson.M{"$set": bson.M{"download": 3}}
//err := Coll.Update(selector, update)
//Update All
update := bson.M{"$set": bson.M{"download": 3}}
_, err := Coll.UpdateAll(selector, update)
if err != nil {
panic(err)
}
}
//Upsert
//db.collection.update(
// <query>,
// <update>,
// {
// upsert: <boolean>,
// multi: <boolean>,
// writeConcern: <document>
// }
//)
func testUpsert() {
fmt.Println("Test Upsert in MongoDB")
//Upsert
update := bson.M{"$inc": bson.M{"download": 3}}
selector := bson.M{"name": "this-is-good-content3"}
_, err := Coll.Upsert(selector, update)
if err != nil {
panic(err)
}
}
//Bulk Upsert
func testBulkUpsert() {
fmt.Println("Test Bulk Upsert in MongoDB")
bulk := Coll.Bulk()
//Upsert
update := bson.M{"$inc": bson.M{"download": 3}}
selector := bson.M{"name": "this-is-good-content3"}
bulk.Upsert(selector, update)
bulk.Upsert(selector, update)
bulk.Upsert(selector, update)
_, err := bulk.Run()
if err != nil {
panic(err)
}
}
//Select
func testSelect() {
fmt.Println("Test Select in MongoDB")
var result Content
var results []Content
var query bson.M
var err error
//query := bson.M{"download": 1}
//Select One
err = Coll.Find(nil).One(&result)
if err != nil {
panic(err)
}
fmt.Printf("Select One: %+v\n", result)
//Select Limit
iter := Coll.Find(nil).Limit(2).Iter()
err = iter.All(&results)
if err != nil {
panic(err)
}
fmt.Printf("Select Limit: %+v\n", results)
//Select All
err = Coll.Find(nil).All(&results)
if err != nil {
panic(err)
}
fmt.Printf("Select All: %+v\n", results)
//Select with query
query = bson.M{"name": "this-is-good-content"}
err = Coll.Find(query).All(&results)
if err != nil {
panic(err)
}
fmt.Printf("Select contentname: %+v\n", results)
//Sort (ascending order)
query = bson.M{"name": "this-is-good-content"}
err = Coll.Find(query).Sort("download").All(&results)
if err != nil {
panic(err)
}
fmt.Printf("Ascending sorted Result: %+v\n", results)
//Sort (descending order)
query = bson.M{"name": "this-is-good-content"}
err = Coll.Find(query).Sort("-download").All(&results) //add - left side
if err != nil {
panic(err)
}
fmt.Printf("Descending sorted Result: %+v\n", results)
}
//Aggregate
func testAggregate() {
pipeline := []bson.M{
{"$match": bson.M{"name": "this-is-good-content" }},
{"$group":
bson.M{"_id": "$date",
//bson.M{"_id": "$name",
"download": bson.M{ "$sum": "$download" },
},
},
{"$sort":
bson.M{"download": 1}, //1: Ascending, -1: Descending
},
}
pipe := Coll.Pipe(pipeline)
result := []bson.M{}
//err := pipe.AllowDiskUse().All(&result) //allow disk use
err := pipe.All(&result)
if err != nil {
panic(err)
}
fmt.Println("result:", result)
}
func main() {
dropDatabase()
//testInsert()
testMultipleInsert()
//testBulkInsert()
//testUpdate()
testUpsert()
//testBulkUpsert()
testSelect()
testAggregate()
}
db.col1.ensureIndex({'colors':1}) # 添加index
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Todo struct {
ID bson.ObjectId `bson:"_id,omitempty"`
Title string
Completed bool
}
var todosCollection *mgo.Collection
var session *mgo.Session
func init() {
session, err := mgo.Dial("127.0.0.1")
if err != nil {
panic(err)
}
session.SetMode(mgo.Monotonic, true)
// get a Collection of todo
todosCollection = session.DB("test-todo").C("todo")
}
func main() {
defer session.Close()
router := gin.Default()
v1 := router.Group("/api/v1/todos")
{
v1.POST("/", createTodo)
v1.GET("/", fetchAllTodo)
v1.GET("/:id", fetchSingleTodo)
v1.PUT("/:id", updateTodo)
v1.DELETE("/:id", deleteTodo)
}
router.Run()
}
func createTodo(context *gin.Context) {
title := context.PostForm("Title")
completed, _ := strconv.ParseBool(context.PostForm("Completed"))
var todo = Todo{bson.NewObjectId(), title, completed}
fmt.Println("" + todo.Title + " completed: " + strconv.FormatBool(todo.Completed))
err := todosCollection.Insert(&todo)
if err != nil {
log.Fatal(err)
}
context.JSON(http.StatusCreated, gin.H{
"status": http.StatusCreated,
"message": "todo item created successfully",
})
}
func fetchAllTodo(context *gin.Context) {
var todos []Todo
err := todosCollection.Find(nil).All(&todos)
if err != nil {
log.Fatal(err)
}
if len(todos) <= 0 {
context.JSON(http.StatusNotFound, gin.H{
"status": http.StatusNotFound,
"message": "no todo found",
})
return
}
context.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"data": todos,
})
}
func fetchSingleTodo(context *gin.Context) {
todo := Todo{}
id := bson.ObjectIdHex(context.Param("id"))
err := todosCollection.FindId(id).One(&todo)
if err != nil || todo == (Todo{}) {
fmt.Println("Error: " + err.Error())
context.JSON(http.StatusNotFound, gin.H{
"status": http.StatusNotFound,
"message": "todo not found",
})
return
}
context.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"data": todo,
})
}
func updateTodo(context *gin.Context) {
id := bson.ObjectIdHex(context.Param("id"))
title := context.PostForm("title")
completed, _ := strconv.ParseBool(context.PostForm("completed"))
err := todosCollection.UpdateId(id, bson.M{"title": title, "completed": completed})
fmt.Printf("completed: %t\n\n", completed)
if err != nil {
fmt.Println("Error: " + err.Error())
context.JSON(http.StatusNotFound, gin.H{
"status": http.StatusNotFound,
"message": "todo not found",
})
return
}
context.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "Todo updated successfully!",
})
}
func deleteTodo(context *gin.Context) {
id := bson.ObjectIdHex(context.Param("id"))
fmt.Printf("id: %v", id)
err := todosCollection.RemoveId(id)
if err != nil {
fmt.Println("Error: " + err.Error())
context.JSON(http.StatusNotFound, gin.H{
"status": http.StatusNotFound,
"message": "todo not found",
})
return
}
context.JSON(http.StatusOK, gin.H{
"status": http.StatusOK,
"message": "Todo deleted successfully!",
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment