01_框架gin笔记

一、安装 go mod init ginchat go get -u github.com/gin-gonic/gin 如果报错输入以下命令解决 go env -w GOPROXY="https://goproxy.io" 或者 go env -w GOPROXY="https://goproxy.cn" go env -w GO111MODULE="on" 还报错就 go env -w GOSUMDB=off 二、基础服务 package main import ( "github.com/gin-gonic/gin" "log" "fmt" ) func main(){ engine:=gin.Default() engine.GET("/hello",func(context *gin.Context){ fmt.Print("hello world:",context.FullPath()) // 后端打印 name:=context.DefaultQuery("name","hello") //获取get请求参数name 如果没有则默认值为 hello context.Writer.Write([]byte("hello,gin\n")) // 前端输出 }) engine.Handle("POST","/login",func(context *gin.Context){ username:=context.PostForm("username") //获取post 参数 username username,exist:=context.GetPostForm("username") // 获取post 参数username 如果存在则exist为ture 否则为false }) // 路径中的变量加冒号 engine.DELETE("/user/:id",func(context *gin.Context){ userId:=context.Param("id") //获取路径中的变量值 }) if err:=engine.Run();err!=nil { log.Fatal(err.Error()) } } 三、请求数据绑定 type Student struct{ Name string `form:"name"` //绑定参数中的name Classes string `form:"classes"` //绑定参数中的classes } 1、绑定get请求数据 var student Student err:= context.ShouldBindQuery(&student) if err != nil { log.Fatal(err.Error()) return } 2、绑定post form 表单请求数据 err:= context.ShouldBind(&student) 可接收 ajax 的object{key:value} 或 form.serialize(key=val&key=val) 数据 3、绑定post json数据 err:=context.BindJSON(&student) 4、解析body type Person struct { Name string `json:"name"` Code string `json:"code"` } json.NewDecoder(context.Request.Body).Decode(&person ) ajax 传 JSON.stringify(objct) 5、接收file file,err:=context.FormFile("file") 四、输出 4.1、context.Writer.Write([]byte("hello")) // 4.2、context.Writer.WriteString("hello") 4.3、context.JSON(200,map[string]interface{}{ "code":1, "message":"请求成功", "data":name, }) 4.4、 type Response struct{ Code int Message string Data interface{} } resp:=Response{Code:1,Message:"ok",Data:name} context.JSON(200,&resp) 4.5、加载html engine.LoadHTMLGlob("./html/*") //加载html资源引擎 enginx.Static("/img","./img") //加载静态资源映射 context.HTML(http.StatusOK,"index.html",nil) context.HTML(http.StatusOK,"index.html",gin.H{ "resp":resp, }) html模板引擎获取数据 {{.resp.Code}} 五、路由组 userGroup :=engine.Group("/user") 六、渲染带html 标签的字符串 app:=gin.Default() app.SetFuncMap(template.FuncMap{ "safe": func(str string) template.HTML { return template.HTML(str) }, "trimHtml": func(src string) string { //将HTML标签全转换成小写 re, _ := regexp.Compile("\\<[\\S\\s]+?\\>") src = re.ReplaceAllStringFunc(src, strings.ToLower) //去除STYLE re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>") src = re.ReplaceAllString(src, "") //去除SCRIPT re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>") src = re.ReplaceAllString(src, "") //去除所有尖括号内的HTML代码,并换成换行符 re, _ = regexp.Compile("\\<[\\S\\s]+?\\>") src = re.ReplaceAllString(src, "\n") //去除连续的换行符 re, _ = regexp.Compile("\\s{2,}") src = re.ReplaceAllString(src, "\n") return strings.TrimSpace(src) }, }) //模板里 {{.content|safe}} //解析html标签 {{.content|trimHtml}} // 去除html标签 userGroup.GET("/login",func(context *gin.Context){})

02_框架gin笔记

六、mysql 安装驱动 go get "github.com/go-sql-driver/mysql" import _ "github.com/go-sql-driver/mysql" import ( _ "github.com/go-sql-driver/mysql" "database/sql" ) connstr:="root:password@tcp(127.0.0.1:3306)databasename" db,err :=sql.Open("mysql",connStr) if err != nil { log.Fatal(err.Error()) return } 创建表 _,err = db.Exec("create table person("+ "id int auto_increment primary key," + "name varchar(12) not null,"+ "age int default 1"+ )") 插入 _,err = db.Exec("insert into person (name,age) values (?,?);","username",18) 查询 type Person struct{ Id int Name string Age int } rows,err:= db.Query("slelect * from person limit 10") scan: if rows.Next(){ person:= new(Person) rows.Scan(&person.Id,&person.Nane,&person.Age) goto scan } 七、定义及调用配置文件 7.1、定义配置文件 config/app.json { "app_name":"cloudrestaurant", "app_mode":"debug", "app_host":"localhost", "app_port":"8080" } 7.2、定义解析配置文件的工具 tools/Config.go package tool import ("os" "bufio" "encoding/json") type Config struct{ AppName string `json:"app_name"` AppMode string `json:"app_name"` AppHost string `json:"app_name"` AppPort string `json:"app_name"` } var _cfg *Config=nil func ParseConfig(path string) (*Config,error){ file,err := os.Open(path) if err !=nil { panic(err) } defer file.Close() reader:=bufio.NewReader(file) decoder:=json.NewDecode(reader) if err:=decoder.Decode(&_cfg);err!=nil{ return nil,err } return _cfg,nil } 八、控制器路由 8.1、controller/HelloController.go package controller import "github.com/gin-goic/gin" type HelloController struct { } func (hello *HelloController) Router(engine *gin.Engine){ engine.GET("hello",hello.Hello) } func (hello *HelloController) Hello(context *gin.Context){ } 8.2、main.go func registerRouter(router *gin.Engine){ new(controller.HelloController).Router(router) } app:=gin.Defult() register() 九、跨域 main.go func Cors() gin.HandlerFunc { return func(context *gin.Context) { method := context.Request.Method context.Header("Access-Control-Allow-Origin", "*") context.Header("Access-Control-Allow-Headers", "Content-Type,AccessToke,X-CSRF-Token,Authorization,Token,x-token") context.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH,PUT") context.Header("Access-Control-Expose-Headers", "Content-Lenth,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Content-Type") context.Header("Access-Control-Allow-Credentials", "true") if method == "OPTIONS" { context.AbortWithStatus(http.StatusNoContent) //context.JSON(http.StatusOK, "Options Request!") } context.Next() } } 使用 app := gin.Default() app.Use(Cors())

04_go-redis、session、cookie

一、redis go get -u github.com/go-redis/redis var redisdb *redis.Client redisdb = redis.New(&redis.Options{ Addr:"127.0.0.1:6379", Password:"", DB:0, }) redisdb.Set("test:name","value",time.Minute * 10) 十分钟失效 二、session go get github.com/gin-contrib/sessions import "github.com/gin-contrib/sessions" 2.1、基于redis使用 在main.go 中 import( "github.com/gin-contrib/sessions" "github.com/gin-contrib/sessions/redis" ) engine:=gin.Default() strore,_:=redis.NewStore(10,"tpc","localhost:6379","",[]byte("secret")) engine.Use(sessions.Sessions("mysession",store)) engine.GET("/path",func(context *gin.Context){ session:=sessions.Default(context) //保存 num:=16 session.Set("count",num) session.Save() //读取 num=session.Get("count") }) json.Marshal(member) //将 member 对象序列化 session.Set("user_id",json.Marshal(member)) 反序列化 var member Member sess:=session.Get("user_id") json.Unmarshal(sess.([]byte),&member) 三、上传图片 file,err:=context.FormFile("file") filename:="./uploadPath/"+strcov.Format(time.Now().Unix(),10)+file.Filename err:=context.SaveUploadFile(file,filename) 四、cookie //设置cookie context.SetCookie("cookie_key","val",10*60,"localhost",true,true) 获取cookie cookie,err:=context.Request.Cookie("cookie_key") const CookieName="cookie_user" const CookieTiimeLen=10*60 func CookieAuth(context *gin.Context) (*http.Cookie,error){ cookie,err:=context.Request.Cookie(CookieName) if err==nil{ context.SetCookie(cookie.Name,cookie.Value,cookie.MaxAge,cookie.Path,cookie.Domain,cookie.Secure,cookie.HttpOnly) return cookie,nil }else{ return nil,err } }

03_xorm

一、安装 go get github.com/go-xorm/xorm 使用示例 // 结构体名称对应数据库表名 type Smscode struct { Id int `xorm:"pk autoincr" json:"id"` Code string `xorm:"varchar(255)" json:"code"` Phone string `xorm:"varchar(255)" json:"phone"` CreateTime int `xorm:"int" json:"create_time"` } import ( _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" ) conn := "root:password@tcp(127.0.0.1:port)/database?charset=utf8mb4" eg, err := xorm.NewEngine("mysql", conn) if err != nil { fmt.Println("链接失败") } fmt.Println("链接成功。。。") eg.ShowSQL(true) //映射结构体,好像没什么卵用 err = eg.Sync2(new(Smscode)) if err != nil { fmt.Println("映射失败") } smsCode := Smscode{Code: "123456", Phone: "15700000000", CreateTime: 12345678910} fmt.Println(smsCode) result, err := eg.InsertOne(smsCode) if err != nil { fmt.Println("插入失败") } fmt.Println(result) //事物 eg, err := xorm.NewEngine("mysql", conn) defer eg.Close() sess:=eg.NewSession() err:=sess.Begin() sess执行sql语句 sess.Rollback() sess.Commit() 条件查询 var sms model.SmsCode // eg,err:= xorm.NewEngine("mysql",[connectString]) _,err:=eg.Where("phone= ? and code = ?",phone,code).Get(&sms) 1.1、service 封装 tool/OrmEngine.go import ( "github.com/go-xorm/xorm" _ "github.com/go-sql-driver/mysql" ) type Orm struct{ *xorm.Engine } var DbEngine *Orm func OrmEngine(cfg *Config) (*Orm,error){ database : = cfg.Database conn:=database.User+":"+database.Password + "@tcp("+database.Host+":"+database.Port+")/"+database.Database+"?charset=utf8" engine,err :=xorm.NewEgine("mysql",conn) if err !=nil { return nil,err } engine.ShowSQL(true) err :=engine.Sync2(new(model.SmsCode)) orm :=new(Orm) orm.Engine =engine DbEngine = orm return orm,nil } 1.2、model调用 model/SmsCode.go type SmsCode struct { Id int64 `xorm:"pk autoincr" json:"id"` Phone string `xorm:"varchar(11)" json:"phone"` CreateTime int64 `xorm:"bigint" json:"create_time"` } 1.3、dao/MemberDao.go type MemberDao struct{ *tool.Orm } func (md *MemberDao) InsertCode(sms model.SmsCode) int64{ result,err :=md.InsertOne(&sms) //返回的是插入的id return result } 1.4、service/MemberService.go 当前时间 time.Now().Unix() smsCode:=model.SmsCode(Phone:phone,Code:code,CreateTime:time.Now().Unix()) memberDao:=dao.MemberDao{} res:=memberDao.InsertCode(smsCode)