[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API

pardon110發表於2019-10-30

本文旨在展示如何使用Go構建restful API 應用,資料庫mongodbcurdhttp錯誤處理

佈局

專案目錄 %GOPATH%\src\pardon110\mogdb_restful內容如下

│  .env
│  main.go
├─env
│      env.go
├─httputil
│      error.go
├─store
│      movie.go
└─storeapi
        movie.go

用法

// go get -u go.mongodb.org/mongo-driver
// go get -u github.com/joho/godotenv

# .env file contents
PORT=8080
DSN=mongodb://localhost:27017

$ go run main.go
> 2019/01/28 05:17:59 Loading environment variables from file: .env
> 2019/01/28 05:17:59 ◽ PORT=8080
> 2019/01/28 05:17:59 ◽ DSN=mongodb://localhost:27017
> Now listening on: http://localhost:8080

效果

增刪改查效果圖
[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API
[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API
[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API
[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API
[實戰] 使用 MongoDB Go 驅動與 Iris 構建 RESTful API

片段

配置載入

func init() {
    envFileName := ".env"

    flagset := flag.CommandLine
    flagset.StringVar(&envFileName, "env", envFileName, "the env file which web app will use to extract its environment variables")
    flag.CommandLine.Parse(os.Args[1:])

    env.Load(envFileName)
}

版本管理與路由分組

....
    app := iris.New()
    // 版本標識 
    app.Use(func(ctx iris.Context) {
        ctx.Header("Server", "Iris MongoDB/"+version)
        ctx.Next()
    })
    // 路由分組
    storeAPI := app.Party("/api/store")
    {
        movieHandler := storeapi.NewMovieHandler(movieService)
        storeAPI.Get("/movies", movieHandler.GetAll)
        storeAPI.Post("/movies", movieHandler.Add)
        storeAPI.Get("/movies/{id}", movieHandler.Get)
        storeAPI.Put("/movies/{id}", movieHandler.Update)
        storeAPI.Delete("/movies/{id}", movieHandler.Delete)
    }

原始碼

RESTful API , 克隆 mogdb_restful 分支

git clone -b mogdb_restful https://gitee.com/pardon110/ShortUrl.git

相關文章