Update code with go mod

This commit is contained in:
2022-03-25 19:31:11 +11:00
parent 51d9f6dc5f
commit cabf977314
14 changed files with 30 additions and 536 deletions
+1
View File
@@ -1,2 +1,3 @@
.env
/forego
.vscode
+10
View File
@@ -0,0 +1,10 @@
module github.com/ddollar/forego
go 1.17
require github.com/subosito/gotenv v1.2.0
require (
github.com/daviddengcn/go-colortext v1.0.0
github.com/stretchr/testify v1.7.1 // indirect
)
+19
View File
@@ -0,0 +1,19 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/daviddengcn/go-colortext v1.0.0 h1:ANqDyC0ys6qCSvuEK7l3g5RaehL/Xck9EX8ATG8oKsE=
github.com/daviddengcn/go-colortext v1.0.0/go.mod h1:zDqEI5NVUop5QPpVJUxE9UO10hRnmkD5G4Pmri9+m4c=
github.com/golangplus/bytes v0.0.0-20160111154220-45c989fe5450/go.mod h1:Bk6SMAONeMXrxql8uvOKuAZSu8aM5RUGv+1C6IJaEho=
github.com/golangplus/bytes v1.0.0/go.mod h1:AdRaCFwmc/00ZzELMWb01soso6W1R/++O1XL80yAn+A=
github.com/golangplus/fmt v1.0.0/go.mod h1:zpM0OfbMCjPtd2qkTD/jX2MgiFCqklhSUFyDW44gVQE=
github.com/golangplus/testing v1.0.0 h1:+ZeeiKZENNOMkTTELoSySazi+XaEhVO0mb+eanrSEUQ=
github.com/golangplus/testing v1.0.0/go.mod h1:ZDreixUV3YzhoVraIDyOzHrr76p6NUh6k/pPg/Q3gYA=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
-22
View File
@@ -1,22 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
-27
View File
@@ -1,27 +0,0 @@
Copyright (c) 2015, David Deng
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of go-colortext nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-21
View File
@@ -1,21 +0,0 @@
go-colortext package [![GoSearch](http://go-search.org/badge?id=github.com%2Fdaviddengcn%2Fgo-colortext)](http://go-search.org/view?id=github.com%2Fdaviddengcn%2Fgo-colortext)
====================
This is a package to change the color of the text and background in the console, working both under Windows and other systems.
Under Windows, the console APIs are used. Otherwise, ANSI texts are output.
Docs: http://godoc.org/github.com/daviddengcn/go-colortext ([packages that import ct](http://go-search.org/view?id=github.com%2fdaviddengcn%2fgo-colortext))
Usage:
```go
Foreground(Green, false)
fmt.Println("Green text starts here...")
ChangeColor(Red, true, White, false)
fmt.Println(...)
ResetColor()
```
LICENSE
=======
BSD license
-47
View File
@@ -1,47 +0,0 @@
/*
ct package provides functions to change the color of console text.
Under windows platform, the Console api is used. Under other systems, ANSI text mode is used.
*/
package ct
// Color is the type of color to be set.
type Color int
const (
// No change of color
None = Color(iota)
Black
Red
Green
Yellow
Blue
Magenta
Cyan
White
)
/*
ResetColor resets the foreground and background to original colors
*/
func ResetColor() {
resetColor()
}
// ChangeColor sets the foreground and background colors. If the value of the color is None,
// the corresponding color keeps unchanged.
// If fgBright or bgBright is set true, corresponding color use bright color. bgBright may be
// ignored in some OS environment.
func ChangeColor(fg Color, fgBright bool, bg Color, bgBright bool) {
changeColor(fg, fgBright, bg, bgBright)
}
// Foreground changes the foreground color.
func Foreground(cl Color, bright bool) {
ChangeColor(cl, bright, None, false)
}
// Background changes the background color.
func Background(cl Color, bright bool) {
ChangeColor(None, false, cl, bright)
}
-35
View File
@@ -1,35 +0,0 @@
// +build !windows
package ct
import (
"fmt"
)
func resetColor() {
fmt.Print("\x1b[0m")
}
func changeColor(fg Color, fgBright bool, bg Color, bgBright bool) {
if fg == None && bg == None {
return
} // if
s := ""
if fg != None {
s = fmt.Sprintf("%s%d", s, 30+(int)(fg-Black))
if fgBright {
s += ";1"
} // if
} // if
if bg != None {
if s != "" {
s += ";"
} // if
s = fmt.Sprintf("%s%d", s, 40+(int)(bg-Black))
} // if
s = "\x1b[0;" + s + "m"
fmt.Print(s)
}
-139
View File
@@ -1,139 +0,0 @@
// +build windows
package ct
import (
"syscall"
"unsafe"
)
var fg_colors = []uint16{
0,
0,
foreground_red,
foreground_green,
foreground_red | foreground_green,
foreground_blue,
foreground_red | foreground_blue,
foreground_green | foreground_blue,
foreground_red | foreground_green | foreground_blue}
var bg_colors = []uint16{
0,
0,
background_red,
background_green,
background_red | background_green,
background_blue,
background_red | background_blue,
background_green | background_blue,
background_red | background_green | background_blue}
const (
foreground_blue = uint16(0x0001)
foreground_green = uint16(0x0002)
foreground_red = uint16(0x0004)
foreground_intensity = uint16(0x0008)
background_blue = uint16(0x0010)
background_green = uint16(0x0020)
background_red = uint16(0x0040)
background_intensity = uint16(0x0080)
foreground_mask = foreground_blue | foreground_green | foreground_red | foreground_intensity
background_mask = background_blue | background_green | background_red | background_intensity
)
var (
kernel32 = syscall.NewLazyDLL("kernel32.dll")
procGetStdHandle = kernel32.NewProc("GetStdHandle")
procSetConsoleTextAttribute = kernel32.NewProc("SetConsoleTextAttribute")
procGetConsoleScreenBufferInfo = kernel32.NewProc("GetConsoleScreenBufferInfo")
hStdout uintptr
initScreenInfo *console_screen_buffer_info
)
func setConsoleTextAttribute(hConsoleOutput uintptr, wAttributes uint16) bool {
ret, _, _ := procSetConsoleTextAttribute.Call(
hConsoleOutput,
uintptr(wAttributes))
return ret != 0
}
type coord struct {
X, Y int16
}
type small_rect struct {
Left, Top, Right, Bottom int16
}
type console_screen_buffer_info struct {
DwSize coord
DwCursorPosition coord
WAttributes uint16
SrWindow small_rect
DwMaximumWindowSize coord
}
func getConsoleScreenBufferInfo(hConsoleOutput uintptr) *console_screen_buffer_info {
var csbi console_screen_buffer_info
ret, _, _ := procGetConsoleScreenBufferInfo.Call(
hConsoleOutput,
uintptr(unsafe.Pointer(&csbi)))
if ret == 0 {
return nil
}
return &csbi
}
const (
std_output_handle = uint32(-11 & 0xFFFFFFFF)
)
func init() {
kernel32 := syscall.NewLazyDLL("kernel32.dll")
procGetStdHandle = kernel32.NewProc("GetStdHandle")
hStdout, _, _ = procGetStdHandle.Call(uintptr(std_output_handle))
initScreenInfo = getConsoleScreenBufferInfo(hStdout)
syscall.LoadDLL("")
}
func resetColor() {
if initScreenInfo == nil { // No console info - Ex: stdout redirection
return
}
setConsoleTextAttribute(hStdout, initScreenInfo.WAttributes)
}
func changeColor(fg Color, fgBright bool, bg Color, bgBright bool) {
attr := uint16(0)
if fg == None || bg == None {
cbufinfo := getConsoleScreenBufferInfo(hStdout)
if cbufinfo == nil { // No console info - Ex: stdout redirection
return
}
attr = getConsoleScreenBufferInfo(hStdout).WAttributes
} // if
if fg != None {
attr = attr & ^foreground_mask | fg_colors[fg]
if fgBright {
attr |= foreground_intensity
} // if
} // if
if bg != None {
attr = attr & ^background_mask | bg_colors[bg]
if bgBright {
attr |= background_intensity
} // if
} // if
setConsoleTextAttribute(hStdout, attr)
}
-1
View File
@@ -1 +0,0 @@
HELLO=world
-2
View File
@@ -1,2 +0,0 @@
*.test
annotate.json
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2013 Alif Rachmawadi
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-102
View File
@@ -1,102 +0,0 @@
# gotenv
Load environment variables dynamically in Go.
|- | - |
|---------------|----------------------------------------------------|
| Build Status | [![Build Status][drone-img]][drone-url] |
| Coverage | [![Coverage Status][coveralls-img]][coveralls-url] |
| Documentation | http://godoc.org/github.com/subosito/gotenv |
## Installation
```bash
$ go get github.com/subosito/gotenv
```
## Usage
Store your configuration to `.env` file on your root directory of your project:
```
APP_ID=1234567
APP_SECRET=abcdef
```
Put the gotenv package on your `import` statement:
```go
import "github.com/subosito/gotenv"
```
Then somewhere on your application code, put:
```go
gotenv.Load()
```
Behind the scene it will then load `.env` file and export the valid variables to the environment variables. Make sure you call the method as soon as possible to ensure all variables are loaded, say, put it on `init()` function.
Once loaded you can use `os.Getenv()` to get the value of the variable.
Here's the final example:
```go
package main
import (
"github.com/subosito/gotenv"
"log"
"os"
)
func init() {
gotenv.Load()
}
func main() {
log.Println(os.Getenv("APP_ID")) // "1234567"
log.Println(os.Getenv("APP_SECRET")) // "abcdef"
}
```
You can also load other than `.env` file if you wish. Just supply filenames when calling `Load()`:
```go
gotenv.Load(".env.production", "credentials")
```
That's it :)
### Another Scenario
Just in case you want to parse environment variables from any `io.Reader`, gotenv keeps its `Parse()` function as public API so you can utilize that.
```go
// import "strings"
pairs := gotenv.Parse(strings.NewReader("FOO=test\nBAR=$FOO"))
// gotenv.Env{"FOO": "test", "BAR": "test"}
pairs = gotenv.Parse(strings.NewReader(`FOO="bar"`))
// gotenv.Env{"FOO": "bar"}
```
Parse ignores invalid lines and returns `Env` of valid environment variables.
### Formats
The gotenv supports various format for defining environment variables. You can see more about it on:
- [fixtures](./fixtures)
- [gotenv_test.go](./gotenv_test.go)
## Notes
The gotenv package is a Go port of [`dotenv`](https://github.com/bkeepers/dotenv) project. Most logic and regexp pattern is taken from there and aims will be compatible as close as possible.
[drone-img]: https://drone.io/github.com/subosito/gotenv/status.png
[drone-url]: https://drone.io/github.com/subosito/gotenv/latest
[coveralls-img]: https://coveralls.io/repos/subosito/gotenv/badge.png?branch=master
[coveralls-url]: https://coveralls.io/r/subosito/gotenv?branch=master
-119
View File
@@ -1,119 +0,0 @@
// Package gotenv provides functionality to dynamically load the environment variables
package gotenv
import (
"bufio"
"io"
"os"
"regexp"
"strings"
)
const (
// Pattern for detecting valid line format
linePattern = `\A(?:export\s+)?([\w\.]+)(?:\s*=\s*|:\s+?)('(?:\'|[^'])*'|"(?:\"|[^"])*"|[^#\n]+)?(?:\s*\#.*)?\z`
// Pattern for detecting valid variable within a value
variablePattern = `(\\)?(\$)(\{?([A-Z0-9_]+)\}?)`
)
// Holds key/value pair of valid environment variable
type Env map[string]string
/*
Load is function to load a file or multiple files and then export the valid variables which found into environment variables.
When it's called with no argument, it will load `.env` file on the current path and set the environment variables.
Otherwise, it will loop over the filenames parameter and set the proper environment variables.
// processing `.env`
gotenv.Load()
// processing multiple files
gotenv.Load("production.env", "credentials")
*/
func Load(filenames ...string) error {
if len(filenames) == 0 {
filenames = []string{".env"}
}
for _, filename := range filenames {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
// set environment
env := Parse(f)
for key, val := range env {
os.Setenv(key, val)
}
}
return nil
}
// Parse if a function to parse line by line any io.Reader supplied and returns the valid Env key/value pair of valid variables.
// It expands the value of a variable from environment variable, but does not set the value to the environment itself.
// This function is skipping any invalid lines and only processing the valid one.
func Parse(r io.Reader) Env {
env := make(Env)
scanner := bufio.NewScanner(r)
for scanner.Scan() {
parseLine(scanner.Text(), env)
}
return env
}
func parseLine(s string, env Env) {
r := regexp.MustCompile(linePattern)
matches := r.FindStringSubmatch(s)
if len(matches) == 0 {
return
}
key := matches[1]
val := matches[2]
// determine if string has quote prefix
hq := strings.HasPrefix(val, `"`)
// trim whitespace
val = strings.Trim(val, " ")
// remove quotes '' or ""
rq := regexp.MustCompile(`\A(['"])(.*)(['"])\z`)
val = rq.ReplaceAllString(val, "$2")
if hq {
val = strings.Replace(val, `\n`, "\n", -1)
// Unescape all characters except $ so variables can be escaped properly
re := regexp.MustCompile(`\\([^$])`)
val = re.ReplaceAllString(val, "$1")
}
rv := regexp.MustCompile(variablePattern)
xv := rv.FindStringSubmatch(val)
if len(xv) > 0 {
var replace string
var ok bool
if xv[1] == "\\" {
replace = strings.Join(xv[2:4], "")
} else {
replace, ok = env[xv[4]]
if !ok {
replace = os.Getenv(xv[4])
}
}
val = strings.Replace(val, strings.Join(xv[0:1], ""), replace, -1)
}
env[key] = val
return
}