Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Created January 13, 2022 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wangpin34/b66ebcc7984e6d689f99b47f1548b0fb to your computer and use it in GitHub Desktop.
Save wangpin34/b66ebcc7984e6d689f99b47f1548b0fb to your computer and use it in GitHub Desktop.
dev on golang, notes, etc
/*
* Covert Goland env to .env format
* e.g.
* Let's say we have env `ENV=production` and `DB=some-db-url` configured in Golang. It will be the following format when it is copiled from the conf.
* ENV=production;DB=some-db-url
* But the popular env format `.env` use the following format:
* ENV=production
* DB=some-db-url
*/
const envStr = 'ENV=production;DB=some-db-url'
class EnvHub {
private envs: Map<string,string>
constructor() {
this.envs = new Map()
}
load(env: string) {
const regExp = /([^;\s]+)=([^;\s]+)/ig
if (!regExp.test(envStr)) {
throw new Error("invalid env string")
}
this.envs = Array.from(envStr.matchAll(regExp)).reduce((a, c) => {
a.set(c[1], c[2])
return a
}, new Map<string, string>())
}
set(k: string, v: string) {
return this.envs.set(k, v)
}
get(k: string) {
return this.envs.get(k)
}
delete(k: string) {
return this.envs.delete(k)
}
toDotEnv() {
const list: string[] = []
for (const [key, value] of this.envs) {
list.push(`${key}=${value}`)
}
return list.join('\n')
}
}
var hub = new EnvHub()
try {
hub.load(envStr)
console.log(hub.toDotEnv())
} catch (err) {
console.error(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment