Gin框架与《Web Development with Go》实践(三)

启动RESTful API应用

在启动http server前,还需要完成以下四步:

  1. 初始化配置值
  2. 载入授权用的键值
  3. 创建一个mongodb的session对象
  4. 给mongodb添加索引

初始化配置值

src/taskmanager2/common2/utils.go

package common2

import (
    "encoding/json"
    "os"
    "log"
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
)

type (
    configuration struct {
        Server, MongoDBHost, DBUser, DBPwd, Database string
        LogLevel int
    }
)

var AppConfig configuration

func initConfig() {
    loadAppConfig()
}

func loadAppConfig() {
    file, err := os.Open("src/taskmanager2/common2/cfg.json")
    defer file.Close()
    if err != nil {
        log.Fatalf("[loadConfig]: %s\n", err)
    }
    decoder := json.NewDecoder(file)
    AppConfig = configuration{}
    err = decoder.Decode(&AppConfig)
    if err != nil {
        log.Fatalf("[loadAppConfig]: %s\n", err)
    }
}

loadAppConfig()中载入cfg.json文件以获取应用参数。
cfg.json(src/taskmanager2/common2/cfg.json)的内容如下(其中的参数都可以自定义):

{
  "Server"      : "0.0.0.0:8890",
  "MongoDBHost" : "192.168.56.99",
  "MongoDBUser" : "",
  "MongoDBPwd"  : "",
  "Database"    : "taskdb",
  "LogLevel"    : 4
}

载入授权用的键值

这里没有使用书中的RSA方式生成公钥私钥,因为其与jwt-go的代码有冲突。可能在新版的jwt-go中有改善。此处的app.k文件中,仅是一个随机字符串而已。
src/taskmanager2/common2/auth.go

const (
    keyPath = "src/taskmanager2/key/app.k"
)
var (
    verifyKey, signKey []byte
)

func initKeys() {
    var err error
    signKey, err = ioutil.ReadFile(keyPath)
    if err != nil {
        log.Fatalf("[initKeys]: %s\n", err)
    }
    verifyKey, err = ioutil.ReadFile(keyPath)
    if err != nil {
        log.Fatalf("[initKeys]: %s\n", err)
    }
}

创建一个mongodb的session对象

src/taskmanager2/common2/mgoUtils.go

package common2

import (
    "log"
    "time"
    "gopkg.in/mgo.v2"
)

var session *mgo.Session

func GetSession() *mgo.Session {
    if session == nil {
        var err error
        session, err = mgo.DialWithInfo(&mgo.DialInfo{
            Addrs: []string{AppConfig.MongoDBHost},
            Username:AppConfig.DBUser,
            Password:AppConfig.DBUser,
            Timeout:60 * time.Second,
        })
        if err != nil {
            log.Fatalf("[GetSession]: %s\n", err)
        }
    }
    return session
}

func createDbSession()  {
    var err error
    session, err = mgo.DialWithInfo(&mgo.DialInfo{
        Addrs:    []string{AppConfig.MongoDBHost},
        Username: AppConfig.DBUser,
        Password: AppConfig.DBPwd,
        Timeout:  60 * time.Second,
    })
    if err != nil {
        log.Fatalf("[createDbSession]: %s\n", err)
    }
}

给mongodb添加索引

src/taskmanager2/common2/mgoUtils.go

func addIndexes() {
    var err error
    userIndex := mgo.Index{
        Key:        []string{"email"},
        Unique:     true,
        Background: true,
        Sparse:     true,
    }
    taskIndex := mgo.Index{
        Key:        []string{"createdby"},
        Unique:     false,
        Background: true,
        Sparse:     true,
    }
    noteIndex := mgo.Index{
        Key:        []string{"taskid"},
        Unique:     false,
        Background: true,
        Sparse:     true,
    }
    session := GetSession().Copy()
    defer session.Close()
    userCol := session.DB(AppConfig.Database).C("users")
    taskCol := session.DB(AppConfig.Database).C("tasks")
    noteCol := session.DB(AppConfig.Database).C("notes")
    err = userCol.EnsureIndex(userIndex)
    if err != nil {
        log.Fatalf("[addIndexes]: %s\n", err)
    }
    err = taskCol.EnsureIndex(taskIndex)
    if err != nil {
        log.Fatalf("[addIndexes]: %s\n", err)
    }
    err = noteCol.EnsureIndex(noteIndex)
    if err != nil {
        log.Fatalf("[addIndexes]: %s\n", err)
    }
}

common包中的初始化逻辑

src/taskmanager2/common2/bootstrapper.go

package common2

// init bootstrapps the application
func init() {
    // Initialize AppConfig variable
    initConfig()

    // Initialize private/public keys for JWT authentication
    initKeys()

    // Initialize Logger objects with Log Level
    setLogLevel(Level(AppConfig.LogLevel))

    // Start a MongoDB session
    createDbSession()

    // Add indexes into MongoDB
    addIndexes()
}

启动http server

src/taskmanager2/main.go

package main

import (
    "log"
    "net/http"
    "time"
    "taskmanager2/routers2"
)

func main() {
    router := routers2.InitRoutes()

    // set server
    server := &http.Server{
        Addr:           ":8890",
        Handler:        router,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Println("Listening...")
    server.ListenAndServe()
}

在gogland中启动:

Gin框架与《Web Development with Go》实践(三)_第1张图片

你可能感兴趣的:(Gin框架与《Web Development with Go》实践(三))