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())