config of pgx is added

This commit is contained in:
병준 박 2019-11-19 23:23:33 +09:00
parent e30c7b7100
commit 3ceae1e399
3 changed files with 68 additions and 22 deletions

View File

@ -22,31 +22,12 @@ type MethodMapping struct {
}
func Run(t reflect.Type) error {
pgURL := &url.URL{
Scheme: "postgres",
User: url.UserPassword("totopia", "totopia"),
Path: "totopia",
}
q := pgURL.Query()
q.Add("sslmode", "disable")
pgURL.RawQuery = q.Encode()
config, err := pgxpool.ParseConfig(pgURL.String())
if err != nil {
pool, err := buildPgx(t)
if nil != err {
return fmt.Errorf("[%v]", err)
}
config.ConnConfig.Host = "localhost"
config.ConnConfig.Port = 54320
pool, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
return fmt.Errorf("[%v]", err)
}
defer pool.Close()
di.RegisterResource("dbConnPool", pool)
taServer := di.GetTypeAnnotation(t, appAnnotation.ServerAnnotationType)
if nil == taServer {
return fmt.Errorf("[%s] is not Server, use @app:Server", t.Elem().Name())
@ -74,6 +55,45 @@ func Run(t reflect.Type) error {
return nil
}
func buildPgx(t reflect.Type) (*pgxpool.Pool, error) {
taPgx := di.GetTypeAnnotation(t, webAnnotation.PgxAnnotationType)
if nil == taPgx {
return nil, fmt.Errorf("[%s] is not Pgx, use @web:Pgx", t.Elem().Name())
}
aPgx := taPgx.(*webAnnotation.PgxAnnotation)
pgURL := &url.URL{
Scheme: "postgres",
User: url.UserPassword(aPgx.User, aPgx.Password),
Path: aPgx.Database,
}
q := pgURL.Query()
if aPgx.SSLMode {
q.Add("sslmode", "enable")
} else {
q.Add("sslmode", "disable")
}
pgURL.RawQuery = q.Encode()
config, err := pgxpool.ParseConfig(pgURL.String())
if err != nil {
return nil, fmt.Errorf("[%v]", err)
}
config.ConnConfig.Host = aPgx.Host
config.ConnConfig.Port = aPgx.Port
pool, err := pgxpool.ConnectConfig(context.Background(), config)
if err != nil {
return nil, fmt.Errorf("[%v]", err)
}
di.RegisterResource("dbConnPool", pool)
return pool, nil
}
func parseRestHandler(restHandler interface{}) *webAnnotation.RestHandlerAnnotation {
t := reflect.TypeOf(restHandler)
ta := di.GetTypeAnnotation(t, webAnnotation.RestHandlerAnnotationType)

View File

@ -0,0 +1,26 @@
package annotation
import (
"reflect"
"git.loafle.net/loafer/annotation-go"
)
var PgxAnnotationType = reflect.TypeOf((*PgxAnnotation)(nil))
func init() {
if err := annotation.Register(PgxAnnotationType); nil != err {
panic(err)
}
}
type PgxAnnotation struct {
annotation.TypeAnnotation `@annotation:"@web:Pgx"`
Host string `json:"host"`
Port uint16 `json:"port"`
Database string `json:"database"`
User string `json:"user"`
Password string `json:"password"`
SSLMode bool `json:"sslMode"`
}

View File

@ -22,5 +22,5 @@ func init() {
}
type Server struct {
annotation.TypeAnnotation `annotation:"@app:Server(\"httpPort\": 8080)"`
annotation.TypeAnnotation `annotation:"@app:Server(\"httpPort\": 8080) @web:Pgx(\"host\": \"localhost\", \"port\": 54320, \"database\": \"totopia\", \"user\": \"totopia\", \"password\": \"totopia\", \"sslMode\": false)"`
}