add options , config

This commit is contained in:
Jay 2018-05-08 16:19:51 +08:00
parent 80e5f0b19c
commit fe884e6931
10 changed files with 172 additions and 12 deletions

View File

@ -0,0 +1,6 @@
database:
user: postgres
password: ""
host: localhost
port: 5432
dbname: gallery

10
main.go
View File

@ -4,18 +4,28 @@ import (
"log"
"git.trj.tw/golang/go-gallery/models"
"git.trj.tw/golang/go-gallery/modules/config"
"git.trj.tw/golang/go-gallery/modules/memstore"
"git.trj.tw/golang/go-gallery/modules/options"
"git.trj.tw/golang/go-gallery/routers/routes"
"github.com/gin-gonic/gin"
)
var server *gin.Engine
func init() {
options.RegFlag()
}
func main() {
err := memstore.InitClient()
if err != nil {
log.Fatal(err)
}
err = config.LoadConfig()
if err != nil {
log.Fatal(err)
}
server = routes.NewServ()
x, err := models.NewDB()
defer x.Close()

View File

@ -2,7 +2,9 @@ package models
import (
"database/sql"
"fmt"
"git.trj.tw/golang/go-gallery/modules/config"
_ "github.com/lib/pq"
)
@ -11,6 +13,8 @@ var x *sql.DB
// NewDB - db object
func NewDB() (*sql.DB, error) {
var err error
x, err = sql.Open("postgres", "user=postgres host=localhost sslmode=disable dbname=gallery")
conf := config.GetConf()
connStr := fmt.Sprintf("user=%s host=%s sslmode=disable dbname=%s port=%d", conf.Database.User, conf.Database.Host, conf.Database.DBName, conf.Database.Port)
x, err = sql.Open("postgres", connStr)
return x, err
}

View File

@ -1,4 +1,66 @@
package config
import (
"errors"
"io/ioutil"
"os"
"path"
"gopkg.in/yaml.v2"
"git.trj.tw/golang/go-gallery/modules/utils"
)
// Config struct
type Config struct {
Database struct {
User string `yaml:"user"`
Password string `yaml:"password"`
Host string `yaml:"host"`
Port int `yaml:"port"`
DBName string `yaml:"dbname"`
} `yaml:"database"`
}
var (
conf *Config
)
// LoadConfig from config file
func LoadConfig(p ...string) error {
var fp string
if len(p) > 0 && len(p[0]) > 0 {
fp = p[0]
} else {
wd, err := os.Getwd()
if err != nil {
return err
}
fp = path.Join(wd, "config.yml")
}
fp = utils.ParsePath(fp)
exists := utils.CheckExists(fp, false)
if !exists {
return errors.New("config file not exists")
}
data, err := ioutil.ReadFile(fp)
if err != nil {
return err
}
conf = &Config{}
err = yaml.Unmarshal(data, conf)
if err != nil {
return err
}
return nil
}
// GetConf get config
func GetConf() *Config {
return conf
}

View File

@ -3,7 +3,6 @@ package middleware
import (
"git.trj.tw/golang/go-gallery/models"
"git.trj.tw/golang/go-gallery/modules/context"
"git.trj.tw/golang/go-gallery/modules/utils"
)
// GetAlbumToNext -
@ -30,8 +29,8 @@ func GetAlbumToNext(c *context.Context) {
return
}
albumMap := utils.ToMap(album)
c.Set("album", albumMap)
// albumMap := utils.ToMap(album)
c.Set("album", album)
c.Next()
}

View File

@ -0,0 +1,25 @@
package options
import (
"flag"
)
// Options -
type Options struct {
Config string
}
var (
opts *Options
)
// RegFlag -
func RegFlag() {
opts = &Options{}
flag.StringVar(&opts.Config, "c", "", "config `file path`")
}
// GetOpts -
func GetOpts() *Options {
return opts
}

View File

@ -1,8 +1,12 @@
package utils
import (
"os"
"path"
"reflect"
"regexp"
"runtime"
"strings"
)
// ToMap struct to map[string]interface{}
@ -30,3 +34,51 @@ func ToMap(ss interface{}) map[string]interface{} {
return smap
}
// ParsePath - parse file path to absPath
func ParsePath(dst string) string {
wd, err := os.Getwd()
if err != nil {
wd = ""
}
if []rune(dst)[0] == '~' {
home := UserHomeDir()
if len(home) > 0 {
dst = strings.Replace(dst, "~", home, -1)
}
}
if path.IsAbs(dst) {
dst = path.Clean(dst)
return dst
}
str := path.Join(wd, dst)
str = path.Clean(str)
return str
}
// UserHomeDir - get user home directory
func UserHomeDir() string {
env := "HOME"
if runtime.GOOS == "windows" {
env = "USERPROFILE"
} else if runtime.GOOS == "plan9" {
env = "home"
}
return os.Getenv(env)
}
// CheckExists - check file exists
func CheckExists(filePath string, allowDir bool) bool {
filePath = ParsePath(filePath)
stat, err := os.Stat(filePath)
if err != nil && !os.IsExist(err) {
return false
}
if !allowDir && stat.IsDir() {
return false
}
return true
}

View File

@ -35,7 +35,7 @@ func GetAllAlbums(c *context.Context) {
// GetAlbum -
func GetAlbum(c *context.Context) {
id := c.Param("id")
id := c.Param("album")
val, ok := c.Get("token")
if !ok {
c.CustomRes("Foridden", "user token data not found")
@ -99,7 +99,7 @@ func CreateAlbum(c *context.Context) {
// UpdateAlbum -
func UpdateAlbum(c *context.Context) {
id := c.Param("id")
id := c.Param("album")
postData := struct {
Name string `json:"name" binding:"required"`
Public bool `json:"public" binding:"required"`
@ -146,7 +146,7 @@ func UpdateAlbum(c *context.Context) {
// DeleteAlbum -
func DeleteAlbum(c *context.Context) {
id := c.Param("id")
id := c.Param("album")
if len(id) == 0 {
c.NotFound(nil)
return

View File

@ -12,12 +12,14 @@ func GetAllAlbumPhotos(c *context.Context) {
// GetPhoto -
func GetPhoto(c *context.Context) {
album, ok := c.Get("album")
data, ok := c.Get("album")
album := data.(models.Album)
if !ok {
c.NotFound("album not found")
return
}
_, err := models.GetPhoto(album.(map[string]interface{})["id"].(string))
_, err := models.GetPhoto(album.ID)
if err != nil {
c.ServerError(nil)
return

View File

@ -51,9 +51,9 @@ func SetDefaultRoutes(r *gin.Engine) {
albumAPI := api.Group("/album", context.PatchContext(middleware.VerifyToken))
{
albumAPI.POST("/", context.PatchContext(album.CreateAlbum))
albumAPI.GET("/:id", context.PatchContext(album.GetAlbum))
albumAPI.PUT("/:id", context.PatchContext(album.UpdateAlbum))
albumAPI.DELETE("/:id", context.PatchContext(album.DeleteAlbum))
albumAPI.GET("/:album", context.PatchContext(album.GetAlbum))
albumAPI.PUT("/:album", context.PatchContext(album.UpdateAlbum))
albumAPI.DELETE("/:album", context.PatchContext(album.DeleteAlbum))
}
photoAPI := albumAPI.Group("/:album/photo", context.PatchContext(middleware.VerifyToken), context.PatchContext(middleware.GetAlbumToNext))
{