go项目技术(部分)
mongo-go-diver
连接数据库,并初始化集合连接
database/mongo.go
var CollectionName *mongo.Collection func InitDB(){ ctx, _ := context.WithTimeout(context.Background(), 10*time.Second) client, err := mongo.Connect(ctx, options.Client().ApplyURI(url)) if err != nil { panic(err) } db := client.Database("web") CollectionName = db.Collection(collectionName) }
main.go
main函数中初始化
func init() { database.InitDB() }
service中的crud
create
插入一个
res,err:=database.CollectionName.InsertOne(context.Background(),model.struct,options...) if err!=nil { ... return }
插入多个
res,err:=database.CollectionName.InsertMany(context.Background(),[]model.struct,options...) if err!=nil { ... return }
find
多项结果
var res []model.struct //数据库获取的结构体数组 data, err := database.CollectionName.Find(context.Background(), bson.M{"sex":sex},options...) if err != nil { ... return } if err = data.All(context.Background(), &res); err != nil { ... return }
仅一项结果
err := database.CollectionName.FindOne(context.Background(), bson.M{"_id": id}).Decode(&model.struct) if err != nil { ... return }
update
which := bson.M{key:value} // 修改哪个 how := bson.M{"$set":bson.M{key:value}} //怎样修改 res, err := database.CollectionName.UpdateOne(context.Background(),which, how,options...) if err != nil { ... return }
delete
res, err := database.CollectionName.DeleteOne(context.Background(), bson.M{"_id": _id}) if err != nil { ... return }
go-redis
初始化redis连接池,建立连接
gredis/gredis.go
var RedisConn *redis.Pool func Setup()error{ RedisConn = &redis.Pool{ Dial: func() (redis.Conn, error) { c,err := redis.Dial("tcp",url) if err!=nil{ fmt.Println("连接失败") return nil, err } return c,err }, } return nil }
main.go
func init() { err := gredis.Setup() if err != nil { panic(err) } }
redis相关操作(未完善)
// Set a key/value func Set(key string, data interface{}, time int) error { conn := RedisConn.Get() defer conn.Close() value, err := json.Marshal(data) if err != nil { return err } _, err = conn.Do("SET", key, value) if err != nil { return err } _, err = conn.Do("EXPIRE", key, time) if err != nil { return err } return nil } // Exists check a key func Exists(key string) bool { conn := RedisConn.Get() defer conn.Close() exists, err := redis.Bool(conn.Do("EXISTS", key)) if err != nil { return false } return exists } // Get get a key func Get(key string) ([]byte, error) { conn := RedisConn.Get() defer conn.Close() reply, err := redis.Bytes(conn.Do("GET", key)) if err != nil { return nil, err } return reply, nil } // Delete delete a kye func Delete(key string) (bool, error) { conn := RedisConn.Get() defer conn.Close() return redis.Bool(conn.Do("DEL", key)) } // LikeDeletes batch delete func LikeDeletes(key string) error { conn := RedisConn.Get() defer conn.Close() keys, err := redis.Strings(conn.Do("KEYS", "*"+key+"*")) if err != nil { return err } for _, key := range keys { _, err = Delete(key) if err != nil { return err } } return nil }
跨域
1、gin有个官方的跨域中间件
https://github.com/gin-contrib/cors
import "github.com/gin-contrib/cors" router.Use(cors.Default())
2、自定义跨域中间件
middleware/cors/cors.go
package Cors import ( "net/http" "github.com/gin-gonic/gin" ) type Options struct { Origin string } func CORS(options Options) gin.HandlerFunc { return func(c *gin.Context) { if options.Origin != "" { c.Writer.Header().Set("Access-Control-Allow-Origin", options.Origin) ////"*"表示接受任意域名的请求,这个值也可以根据自己需要,设置成不同域名 } c.Writer.Header().Set("Access-Control-Max-Age", "86400") c.Writer.Header().Set("Access-Control-Allow-Methods", "*") c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization,ID,Authority,*") // 允许自定义header c.Writer.Header().Set("Access-Control-Expose-Headers", "*") c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") if c.Request.Method == "OPTIONS" { c.AbortWithStatus(http.StatusNoContent) } else { c.Next() } } }