The Seven Year Itch.

MENU

使用Go的框架前要准备的工作之 - 搭建基础的项目框架(一)

January 9, 2019 • Read: 52 • Go

项目框架目录结构

在go中 方法首字母大写和大写开头的都是表示外部可以调用的.

gshell
└── master
    ├── apps
    │   ├── ApiServer.go
    │   ├── Config.go
    │   └── models.go
    ├── config
    │   └── g_shell.json
    └── main
        └── gshell.go

1.1 main包的编写

入口文件主要做一些初始化操作和读取配置的操作

package main

import (
    "awesomeProject/gshell/master/apps"
    "flag"
    "fmt"
    "runtime"
)

var (
    confFile string
)

func initArgs() {
    // 解析命令行命令
    flag.StringVar(&confFile, "config", "../config/g_shell.json", "指定master路径")
    flag.Parse()
}

func initEnv() {
    // 初始化线程
    runtime.GOMAXPROCS(runtime.NumCPU())
}

func main() {

    var (
        err error
    )
    // 初始化命令行参数
    initArgs()

    // 初始化线程
    initEnv()

    if err = apps.InitConfig(confFile); err != nil {
        goto ERR
    }
    // 初始化数据库
    apps.MysqlConnect()
    // 初始化服务
    apps.InitApiServer()
    return

ERR:
    fmt.Println(err)
}

1.2 apps目录中编写config文件

package apps

import (
    "encoding/json"
    "io/ioutil"
)

type Config struct {
    ApiPort    int    `json:"api_port"`
    DbUri string `json:"db_uri"`
}

var (
    // 外部可以引入配置
    C *Config
)

func InitConfig(filename string) (err error) {
    var (
        content []byte
        conf    Config
    )

    // 读取配置文件

    if content, err = ioutil.ReadFile(filename); err != nil {
        panic(err)
    }

    // Json反序列化
    if err = json.Unmarshal(content, &conf); err != nil {
        panic(err)
    }

    C = &conf # 

    return
}

1.3 models的编写

package apps

import (
    _ "github.com/astaxie/beego/validation"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
    db  *gorm.DB
    err error
)

type User struct {
    gorm.Model
    Username string `valid:"Required"`
    Password string `valid:"Required"`
    Email    string `valid:"Email;MaxSize(100)"`
    Phone    string `valid:"Mobile"`
}

var (
    MUser *User
)

func MysqlConnect() {
    var (
        users User
    )
    if db, err = gorm.Open("mysql", C.DbUri); err != nil {
        panic("数据库连接失败!")
    }

    MUser = &users

    return
}

1.4 Api的编写(这个其实是要和第一步并行的)

package apps

import (
    _ "github.com/astaxie/beego/validation"
    _ "github.com/go-sql-driver/mysql"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

var (
    db  *gorm.DB
    err error
)

type User struct {
    gorm.Model
    Username string `valid:"Required"`
    Password string `valid:"Required"`
    Email    string `valid:"Email;MaxSize(100)"`
    Phone    string `valid:"Mobile"`
}

var (
    MUser *User
)

func MysqlConnect() {
    var (
        users User
    )
    if db, err = gorm.Open("mysql", C.DbUri); err != nil {
        panic("数据库连接失败!")
    }

    MUser = &users

    return
}


gits 地址

Tags: None
Archives QR Code
QR Code for this page
Tipping QR Code