golang后端开发之功能deamo

基于ferry项目学习总结
代码地址:https://gitee.com/yllan/ferry

1.启动http服务(go关键字)

        //用go func() run http服务
        go func() {  
                srv := &http.Server{
                  Addr:    config2.ApplicationConfig.Host + ":" + config2.ApplicationConfig.Port,
              Handler: r,
      }
      if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            logger.Fatalf("listen: %s\n", err)
          }
          }()
    quit := make(chan os.Signal)  //使用无缓存chan阻塞go func()退出
    signal.Notify(quit, os.Interrupt)  //signal.Notify监听中断事件退出go func()
    <-quit
        // 中断后优雅关闭服务器(设置 5 秒的超时时间)
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        logger.Fatal("Server Shutdown:", err)
    }
    logger.Info("Server exiting")
    return nil

2.定义全局变量(import xxx from xxx)

一组变量全局使用
package config
import "github.com/spf13/viper"
type Database struct {   
    Dbtype   string
        xxx    string
        xxx    string
}
func InitDatabase(cfg *viper.Viper) *Database {
    return &Database{
        Dbtype:   cfg.GetString("dbType"),
    }
}
var DatabaseConfig = new(Database)
var cfgDatabase *viper.Viper
func ConfigSetup(path string) {
    viper.SetConfigFile(path) //viper工具加载指定路径配置文件
    content, err := ioutil.ReadFile(path) //读取文件内容
    err = viper.ReadConfig(strings.NewReader(os.ExpandEnv(string(content))))
    cfgDatabase = viper.Sub("settings.database")
    DatabaseConfig = InitDatabase(cfgDatabase)  //调用InitDatabase方法,实例化DatabaseConfig
}

全局使用方法import config2 from config
config2.DatabaseConfig.Dbtype


方法2: 
从配置文件获取单个值
import "github.com/spf13/viper"
mode:=viper.GetString("settings.application.mode") 

3.一键初始化,cobra库应用(mysql自动建表,启动任务队列,mysql新建连接等)

var rootCmd = &cobra.Command{
    Use:               "ferry",
    Short:             "-v",
    SilenceUsage:      true,
    DisableAutoGenTag: true,
    Long:              `ferry`,
    PersistentPreRunE: func(*cobra.Command, []string) error { return nil },
    Run: func(cmd *cobra.Command, args []string) {
        usageStr := `欢迎使用 ferry,可以使用 -h 查看命令`
        logger.Infof("%s\n", usageStr)
    },
}
func init() {
    rootCmd.AddCommand(api.StartCmd)  //加两个二级命令参数
    rootCmd.AddCommand(migrate.StartCmd)
}

//migrate.StartCmd
var (
    StartCmd = &cobra.Command{
        Use:   "init",
        Short: "initialize the database",
        Run: func(cmd *cobra.Command, args []string) {
            run()
        },
    }
)
func init() {
    StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/settings.yml", "Start server with provided configuration file")
    StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
}
func run() {
    config2.ConfigSetup(config)  //设置全局变量
    database.Setup()  //新建数据库连接
    _ = migrateModel()  //自动建表
       system.InitDb()  //导入测试数据
}

//api.StartCmd
var (
    StartCmd = &cobra.Command{
        Use:     "server",
        Short:   "Start API server",
        Example: "ferry server config/settings.yml",
        PreRun: func(cmd *cobra.Command, args []string) {  //先执行
            setup()
        },
        RunE: func(cmd *cobra.Command, args []string) error { //后执行
            return run()
        },
    }
)
func init() {
    StartCmd.PersistentFlags().StringVarP(&config, "config", "c", "config/settings.yml", "Start server with provided configuration file")
    StartCmd.PersistentFlags().StringVarP(&port, "port", "p", "8002", "Tcp port server listening on")
    StartCmd.PersistentFlags().StringVarP(&mode, "mode", "m", "dev", "server mode ; eg:dev,test,prod")
}
func setup() {
    config2.ConfigSetup(config)  //设置全局变量
    database.Setup()  //新建数据库连接
    go task.Start() //启动任务队列
}
func run() error {  //启动http服务
    config2.SetConfig(config, "settings.application.mode", mode)
    gin.SetMode(gin.ReleaseMode
    r := router.InitRouter()
    defer func() {
        err := orm.Eloquent.Close()
        if err != nil {
            logger.Error(err)
        }
    }()
    config2.SetConfig(config, "settings.application.port", port)
    srv := &http.Server{
        Addr:    config2.ApplicationConfig.Host + ":" + config2.ApplicationConfig.Port,
        Handler: r,
    }
    go func() {
            if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
                logger.Fatalf("listen: %s\n", err)
            }
    }()
    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt)
    <-quit
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
}

4.mysql自动建表

type CasbinRule struct {
    Id    int    `gorm:"primary_key;AUTO_INCREMENT;column:id" json:"id" form:"id"`
    BaseModel
}
func (CasbinRule) TableName() string {
    return "casbin_rule"
}

import "github.com/jinzhu/gorm"
type Database interface {
    Open(dbType string, conn string) (db *gorm.DB, err error)
}
var db Database
db = new(Mysql)
Eloquent, err = gorm.Open(dbType string, conn string)
Eloquent.AutoMigrate( 
    new(system.CasbinRule)   //自动创建名为casbin_rule的表
)

你可能感兴趣的:(golang后端开发之功能deamo)