简体   繁体   中英

Separting the development and production environment in GOLANG

I am new to GO programming. I came from nodejs. It was easy to separate the dev and prod mode in nodejs. By simply using this code.

if(process.env.NODE_ENV==="production"){
   server.listen(prod.port);
} 
else{
   server.listen(dev.port);
}

I basically want this convention to use in GO too. So how could I separate my dev and production code.

The reason why want this feature is

to separate the port my server is listening in dev and prod environment

If there is any technique to separate the port, It would work either.

PS: I am using VScode as my code editor. And go-iris as a go server framework

you can use os.Getenv function.

package main

import (
    "fmt"
    "os"
)

func getEnv() string{
    return os.Getenv("APP_ENV")
}

https://golang.org/src/os/env.go?s=2471:2501#L73

There are multiple ways you can achieve this in Go, but all of them do not handle this in the code itself.

  1. Use environment variables, eg os.Getenv
  2. Parse config files, eg some .yaml file
  3. Use flags, eg package flag

I think the most common solution is using flags but all do the same job. Usually you parse your flags in the main method.

Just run your application with arguments, such as go run main.go -mode development , while the default mode is production. You can start your application with scripts in order to seperate different environments. For example, your bootstrap.bat file may look like this: go run main.go -mode development .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM