英文:
how to create dinamic port in golang (echo framwork)
问题
我在这里为你翻译代码部分:
package config
import (
"fmt"
logger "github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DatabaseConnect() *gorm.DB {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", pkg.GodotEnv("DB_HOST"), pkg.GodotEnv("DB_PORT"), pkg.GodotEnv("DB_USER"), pkg.GodotEnv("DB_NAME"), pkg.GodotEnv("DB_PASSWORD"))
db, err := gorm.Open(postgres.Open(DBURL), &gorm.Config{})
if err != nil {
defer logger.Info("Database connection failed")
logger.Fatal(err)
return nil
}
return db
}
和 main.go:
func main() {
e := echo.New()
db := config.DatabaseConnect()
middleware.WebSecurityConfig(e)
routes.NewRoute(db, e)
e.Logger.Fatal(e.Start(":8080"))
}
你想要创建一个像下面示例中的动态路由:
server.Initialize(os.Getenv("DB_DRIVER"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_PORT"), os.Getenv("DB_HOST"), os.Getenv("DB_NAME"))
server.Run(":" + os.Getenv("PORT"))
如何创建动态端口服务器?谢谢。
英文:
i have package config.go in this my code
package config
import (
"fmt"
logger "github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DatabaseConnect() *gorm.DB {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", pkg.GodotEnv("DB_HOST"), pkg.GodotEnv("DB_PORT"), pkg.GodotEnv("DB_USER"), pkg.GodotEnv("DB_NAME"), pkg.GodotEnv("DB_PASSWORD"))
db, err := gorm.Open(postgres.Open(DBURL), &gorm.Config{})
if err != nil {
defer logger.Info("Database connection failed")
logger.Fatal(err)
return nil
}
return db
}
and main.go
func main() {
e := echo.New()
db := config.DatabaseConnect()
middleware.WebSecurityConfig(e)
routes.NewRoute(db, e)
e.Logger.Fatal(e.Start(":8080"))
}
I want to create a dynamic routing like the example below :
server.Initialize(os.Getenv("DB_DRIVER"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_PORT"), os.Getenv("DB_HOST"), os.Getenv("DB_NAME"))
server.Run(":" + os.Getenv("PORT"))
how to create dinamic port server ? thanks
答案1
得分: 2
请看这个链接:https://github.com/joho/godotenv。
将应用程序的配置添加到项目根目录下的.env文件中:
DB_DRIVER=mysql
DB_USER=root
...
然后在你的Go应用程序中可以这样做:
package main
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("加载.env文件时出错")
}
driver:= os.Getenv("DB_DRIVER")
user:= os.Getenv("DB_USER")
// todo
}
英文:
Check this out: https://github.com/joho/godotenv.
Add your application configuration to your .env file in the root of your project:
DB_DRIVER=mysql
DB_USER=root
...
Then in your Go app you can do something like:
package main
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
driver:= os.Getenv("DB_DRIVER")
user:= os.Getenv("DB_USER")
// todo
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论