Compare commits
14 Commits
v0.0.1-dev
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| 781204fd87 | |||
| 5df8d5f7ae | |||
| 992ccd98b3 | |||
| 48ccd03be5 | |||
| a7c9333685 | |||
| b7143ed450 | |||
| e100208845 | |||
| 9d4fe2a78d | |||
| 10a5bd4cc4 | |||
| 5fa031c802 | |||
| cd146dc643 | |||
| 33e2e45346 | |||
| 136d2fde51 | |||
| 9d85908628 |
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,5 +1,5 @@
|
||||
# ---> Go
|
||||
# Binaries for programs and plugins
|
||||
bin
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
@ -12,3 +12,4 @@
|
||||
# Output of the go coverage tool, specifically when used with LiteIDE
|
||||
*.out
|
||||
|
||||
/.env
|
||||
|
||||
17
Makefile
Normal file
17
Makefile
Normal file
@ -0,0 +1,17 @@
|
||||
BIN_NAME=gotest
|
||||
PACKAGE_NAME=git.bloy.org/mike/gotest
|
||||
GIT_DESCRIBE=$(shell git describe --always --long --dirty)
|
||||
LDFLAGS="-X ${PACKAGE_NAME}/version.gitDescribe=${GIT_DESCRIBE}"
|
||||
|
||||
default: all
|
||||
|
||||
all: test build
|
||||
|
||||
build:
|
||||
go build -ldflags ${LDFLAGS} -o bin/${BIN_NAME}
|
||||
|
||||
test:
|
||||
go test ./... -ldflags ${LDFLAGS}
|
||||
|
||||
clean:
|
||||
rm -rf bin/${BIN_NAME}
|
||||
23
cmd/logtest.go
Normal file
23
cmd/logtest.go
Normal file
@ -0,0 +1,23 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(logtestCmd)
|
||||
}
|
||||
|
||||
var logtestCmd = &cobra.Command{
|
||||
Use: "logtest",
|
||||
Short: "Test logging",
|
||||
Long: "Test logging",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
log.WithField("msg-id", 11987).Trace("This is a trace")
|
||||
log.WithField("bob", "your uncle").Debug("This is debug")
|
||||
log.WithField("userid", "mike").Info("This is an info")
|
||||
log.WithField("jenny", 8675309).Warn("This is a warning")
|
||||
log.WithField("OMG", "Ponies").Error("This is an error")
|
||||
},
|
||||
}
|
||||
62
cmd/root.go
Normal file
62
cmd/root.go
Normal file
@ -0,0 +1,62 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/kyoh86/xdg"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var cfgFile string
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "gotest",
|
||||
Short: "Gotest is a thing for testing out go packaging and boilerplate",
|
||||
Long: "An Experiment",
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
viper.SetDefault("addr", ":8000")
|
||||
viper.SetDefault("env", "production")
|
||||
rootCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c",
|
||||
"", "Full path to config file")
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
viper.SetEnvPrefix("gotest")
|
||||
viper.AutomaticEnv()
|
||||
if cfgFile != "" {
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
for _, p := range xdg.AllConfigDirs() {
|
||||
viper.AddConfigPath(p)
|
||||
}
|
||||
viper.SetConfigName("gotest")
|
||||
}
|
||||
viper.ReadInConfig()
|
||||
if viper.GetString("env") == "production" {
|
||||
log.SetFormatter(&log.JSONFormatter{})
|
||||
log.SetOutput(os.Stdout)
|
||||
} else {
|
||||
log.SetFormatter(&log.JSONFormatter{
|
||||
PrettyPrint: true,
|
||||
FieldMap: log.FieldMap{
|
||||
log.FieldKeyLevel: "priority",
|
||||
log.FieldKeyTime: "timestamp",
|
||||
log.FieldKeyMsg: "message",
|
||||
},
|
||||
DataKey: "opt"})
|
||||
}
|
||||
}
|
||||
|
||||
// Execute the root command
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
20
cmd/run.go
Normal file
20
cmd/run.go
Normal file
@ -0,0 +1,20 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"git.bloy.org/mike/gotest/web"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(runCmd)
|
||||
runCmd.Flags().String("addr", ":8000", "Port to serve http")
|
||||
}
|
||||
|
||||
var runCmd = &cobra.Command{
|
||||
Use: "run",
|
||||
Short: "Run the webserver",
|
||||
Long: "Listen to the specified port and serve http until interrupted",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
web.RunServer()
|
||||
},
|
||||
}
|
||||
33
cmd/version.go
Normal file
33
cmd/version.go
Normal file
@ -0,0 +1,33 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"git.bloy.org/mike/gotest/version"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var showCfg bool
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
versionCmd.Flags().BoolVarP(&showCfg, "long", "l", false,
|
||||
"Show the configuration as well as the version")
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: "All software has versions. This is how you see it.",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("This is GoTest %s\n\n", version.Version)
|
||||
fmt.Printf(" Config location: %s\n", viper.ConfigFileUsed())
|
||||
if showCfg {
|
||||
fmt.Println("\nConfiguration Data:")
|
||||
for _, key := range viper.AllKeys() {
|
||||
fmt.Printf(" %s: %t\n", key, viper.Get(key))
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
10
go.mod
10
go.mod
@ -1,3 +1,13 @@
|
||||
module git.bloy.org/mike/gotest
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.1.1
|
||||
github.com/gorilla/mux v1.7.3
|
||||
github.com/joho/godotenv v1.3.0
|
||||
github.com/kyoh86/xdg v1.0.0
|
||||
github.com/sirupsen/logrus v1.4.2
|
||||
github.com/spf13/cobra v0.0.5
|
||||
github.com/spf13/viper v1.3.2
|
||||
)
|
||||
|
||||
61
go.sum
Normal file
61
go.sum
Normal file
@ -0,0 +1,61 @@
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
||||
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
||||
github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk=
|
||||
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||
github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY=
|
||||
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
|
||||
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/joho/godotenv v1.3.0 h1:Zjp+RcGpHhGlrMbJzXTrZZPrWj+1vfm90La1wgB6Bhc=
|
||||
github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kyoh86/xdg v1.0.0 h1:TD1layQ0epNApNwGRblnQnT3S/2UH/gCQN1cmXWotvE=
|
||||
github.com/kyoh86/xdg v1.0.0/go.mod h1:Z5mDqe0fxyxn3W2yTxsBAOQqIrXADQIh02wrTnaRM38=
|
||||
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
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/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
|
||||
github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4=
|
||||
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
|
||||
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/cobra v0.0.5 h1:f0B+LkLX6DtmRH1isoNA9VTtNUK9K8xYd28JNNfOv/s=
|
||||
github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU=
|
||||
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/viper v1.3.2 h1:VUFqw5KcqRf7i70GOzW7N+Q7+gxVBkSSqiXB12+JQ4M=
|
||||
github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0=
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a h1:1n5lsVfiQW3yfsRGu98756EH1YthsFqr/5mxHduZW2A=
|
||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894 h1:Cz4ceDQGXuKRnVBDTS23GTn/pU5OE2C0WrNTOYK1Uuc=
|
||||
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
11
main.go
11
main.go
@ -1,11 +1,10 @@
|
||||
package main
|
||||
|
||||
import "fmt"
|
||||
import (
|
||||
"git.bloy.org/mike/gotest/cmd"
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println(sayHi("Mike"))
|
||||
}
|
||||
|
||||
func sayHi(name string) string {
|
||||
return fmt.Sprintf("Hi %s", name)
|
||||
cmd.Execute()
|
||||
}
|
||||
|
||||
12
main_test.go
12
main_test.go
@ -1,12 +0,0 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSayHi(t *testing.T) {
|
||||
expected := "Hi Testy"
|
||||
greeting := sayHi("Testy")
|
||||
if greeting != expected {
|
||||
t.Errorf("Greeting was incorrect, got: '%s', want: '%s'",
|
||||
greeting, expected)
|
||||
}
|
||||
}
|
||||
119
version/version.go
Normal file
119
version/version.go
Normal file
@ -0,0 +1,119 @@
|
||||
// Package version implements version parsing logic
|
||||
package version
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// gitDescribe : Git's "git describe --always --dirty" output
|
||||
var gitDescribe = ""
|
||||
|
||||
// GoVersion : The go version used to compile this binary
|
||||
var GoVersion = runtime.Version()
|
||||
|
||||
// OsArch : The OS and archetcture used for this binary
|
||||
var OsArch = fmt.Sprintf("%s (%s)", runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
// Version : the complete version data
|
||||
var Version = parseGitDescribe(gitDescribe)
|
||||
|
||||
// Info : data structure for program version information
|
||||
type info struct {
|
||||
Major int
|
||||
Minor int
|
||||
Patch int
|
||||
Prerelease []string
|
||||
BuildMeta []string
|
||||
}
|
||||
|
||||
// Equal compares two Info structs for equality
|
||||
func (i info) Equal(o info) bool {
|
||||
if i.Major != o.Major || i.Minor != o.Minor || i.Patch != o.Patch {
|
||||
return false
|
||||
}
|
||||
if len(i.Prerelease) != len(o.Prerelease) || len(i.BuildMeta) != len(o.BuildMeta) {
|
||||
return false
|
||||
}
|
||||
for j := 0; j < len(i.Prerelease); j++ {
|
||||
if i.Prerelease[j] != o.Prerelease[j] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for j := 0; j < len(i.BuildMeta); j++ {
|
||||
if i.BuildMeta[j] != o.BuildMeta[j] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// String returns a human friendly version string
|
||||
func (i info) String() string {
|
||||
var b strings.Builder
|
||||
fmt.Fprintf(&b, "v%d.%d.%d", i.Major, i.Minor, i.Patch)
|
||||
if len(i.Prerelease) > 0 {
|
||||
fmt.Fprintf(&b, "-%s", strings.Join(i.Prerelease, "."))
|
||||
}
|
||||
if len(i.BuildMeta) > 0 {
|
||||
fmt.Fprintf(&b, "+%s", strings.Join(i.BuildMeta, "."))
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
/* reStr is a regular expression string to parse the output of git describe
|
||||
Match groups:
|
||||
|
||||
1. version number (without "v")
|
||||
2. major version
|
||||
3. minor version
|
||||
4. patch version
|
||||
5. prerelease identifier
|
||||
6. commit count
|
||||
7. git short hash
|
||||
8. "-dirty" if dirty, else ""
|
||||
*/
|
||||
const reStr = `^(?:v(([0-9]+)(?:\.([0-9]+)(?:\.([0-9]+))?)?))?(?:-((?:alpha|beta|rc|dev)(?:\.[a-zA-Z0-9]+)*))?(?:-([0-9]+)-g)?([a-f0-9A-F]+)?(?:(-dirty))?$`
|
||||
|
||||
var re = regexp.MustCompile(reStr)
|
||||
|
||||
func parseGitDescribe(input string) info {
|
||||
matches := re.FindStringSubmatch(input)
|
||||
if matches == nil || matches[0] == "" {
|
||||
return info{0, 0, 0, []string{"dev"}, []string{"unknown"}}
|
||||
}
|
||||
|
||||
info := info{}
|
||||
if matches[2] != "" {
|
||||
num, _ := strconv.Atoi(matches[2])
|
||||
info.Major = num
|
||||
}
|
||||
if matches[3] != "" {
|
||||
num, _ := strconv.Atoi(matches[3])
|
||||
info.Minor = num
|
||||
}
|
||||
if matches[4] != "" {
|
||||
num, _ := strconv.Atoi(matches[4])
|
||||
info.Patch = num
|
||||
}
|
||||
if matches[5] != "" {
|
||||
info.Prerelease = strings.Split(matches[5], ".")
|
||||
}
|
||||
if matches[6] != "" || matches[7] != "" || matches[8] != "" {
|
||||
info.BuildMeta = append(info.BuildMeta, "git")
|
||||
if matches[6] != "" {
|
||||
info.BuildMeta = append(info.BuildMeta, matches[6])
|
||||
}
|
||||
if matches[7] != "" {
|
||||
info.BuildMeta = append(info.BuildMeta, matches[7])
|
||||
}
|
||||
if matches[8] != "" {
|
||||
info.BuildMeta = append(info.BuildMeta, "dirty")
|
||||
}
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
77
version/version_test.go
Normal file
77
version/version_test.go
Normal file
@ -0,0 +1,77 @@
|
||||
package version
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGoVersion(t *testing.T) {
|
||||
got := GoVersion
|
||||
expected := runtime.Version()
|
||||
if got != expected {
|
||||
t.Errorf("Expected: %s ; Got: %s", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOsArch(t *testing.T) {
|
||||
got := OsArch
|
||||
expected := runtime.GOOS + " (" + runtime.GOARCH + ")"
|
||||
if got != expected {
|
||||
t.Errorf("Expected: %s ; Got: %s", got, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGitDescribe(t *testing.T) {
|
||||
expected := []info{
|
||||
info{0, 0, 0, []string{"dev"}, []string{"unknown"}},
|
||||
info{0, 0, 0, []string{}, []string{"git", "feedbeef"}},
|
||||
info{1, 2, 0, []string{"dev", "1"}, []string{"git", "83", "feedbeef"}},
|
||||
info{1, 2, 3, []string{"dev", "1"}, []string{"git", "83", "feedbeef", "dirty"}},
|
||||
info{1, 2, 3, []string{}, []string{"git", "dirty"}},
|
||||
info{1, 2, 3, []string{"beta"}, []string{"git", "dirty"}},
|
||||
info{1, 2, 3, []string{"rc"}, []string{}},
|
||||
}
|
||||
inputs := []string{
|
||||
"",
|
||||
"feedbeef",
|
||||
"v1.2-dev.1-83-gfeedbeef",
|
||||
"v1.2.3-dev.1-83-gfeedbeef-dirty",
|
||||
"v1.2.3-dirty",
|
||||
"v1.2.3-beta-dirty",
|
||||
"v1.2.3-rc",
|
||||
}
|
||||
for i := 0; i < len(expected); i++ {
|
||||
got := parseGitDescribe(inputs[i])
|
||||
if !expected[i].Equal(got) {
|
||||
t.Errorf("Got: %v, Expected: %v", got, expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInfoStringer(t *testing.T) {
|
||||
inputs := []info{
|
||||
info{0, 0, 0, []string{"dev"}, []string{"unknown"}},
|
||||
info{0, 0, 0, []string{}, []string{"git", "feedbeef"}},
|
||||
info{1, 2, 0, []string{"dev", "1"}, []string{"git", "83", "feedbeef"}},
|
||||
info{1, 2, 3, []string{"dev", "1"}, []string{"git", "83", "feedbeef", "dirty"}},
|
||||
info{1, 2, 3, []string{}, []string{"git", "dirty"}},
|
||||
info{1, 2, 3, []string{"beta"}, []string{"git", "dirty"}},
|
||||
info{1, 2, 3, []string{"rc"}, []string{}},
|
||||
}
|
||||
expected := []string{
|
||||
"v0.0.0-dev+unknown",
|
||||
"v0.0.0+git.feedbeef",
|
||||
"v1.2.0-dev.1+git.83.feedbeef",
|
||||
"v1.2.3-dev.1+git.83.feedbeef.dirty",
|
||||
"v1.2.3+git.dirty",
|
||||
"v1.2.3-beta+git.dirty",
|
||||
"v1.2.3-rc",
|
||||
}
|
||||
for i := 0; i < len(expected); i++ {
|
||||
got := fmt.Sprint(inputs[i])
|
||||
if got != expected[i] {
|
||||
t.Errorf("Got: %v, Expected: %v", got, expected[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
150
web/middleware.go
Normal file
150
web/middleware.go
Normal file
@ -0,0 +1,150 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type contextKey int
|
||||
|
||||
// context keys to be used when inspecting request contexts
|
||||
const (
|
||||
requestIDKey contextKey = iota
|
||||
correlationIDKey
|
||||
loggerKey
|
||||
)
|
||||
|
||||
// Header names for middleware to use
|
||||
const (
|
||||
RequestIDHeader string = "X-Request-Id"
|
||||
CorrelationIDHeader = "X-Correlation-Id"
|
||||
)
|
||||
|
||||
// CorrelationIDFromRequest gets a correlation id from the request, if it
|
||||
// exists.
|
||||
func CorrelationIDFromRequest(req *http.Request) string {
|
||||
var id string
|
||||
if str := req.Header.Get(CorrelationIDHeader); str != "" {
|
||||
id = str
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
func getFromContext(ctx context.Context, key contextKey) (value string, ok bool) {
|
||||
if v := ctx.Value(key); v != nil {
|
||||
value = v.(string)
|
||||
ok = true
|
||||
return
|
||||
}
|
||||
value, ok = "", false
|
||||
return
|
||||
}
|
||||
|
||||
func CorrelationIDFromContext(ctx context.Context) (value string, ok bool) {
|
||||
return getFromContext(ctx, correlationIDKey)
|
||||
}
|
||||
|
||||
func RequestIDFromContext(ctx context.Context) (value string, ok bool) {
|
||||
return getFromContext(ctx, requestIDKey)
|
||||
}
|
||||
|
||||
func LoggerFromContext(ctx context.Context) *log.Entry {
|
||||
if v := ctx.Value(loggerKey); v != nil {
|
||||
return v.(*log.Entry)
|
||||
}
|
||||
return log.WithFields(log.Fields{})
|
||||
}
|
||||
|
||||
type loggingResponseWriter struct {
|
||||
http.ResponseWriter
|
||||
size, status int
|
||||
start time.Time
|
||||
}
|
||||
|
||||
// This idea is taken from the violetear responsewriter
|
||||
// https://github.com/nbari/violetear/blob/master/responsewriter.go
|
||||
func newLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
|
||||
return &loggingResponseWriter{
|
||||
ResponseWriter: w,
|
||||
start: time.Now(),
|
||||
status: http.StatusOK,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *loggingResponseWriter) Status() int {
|
||||
return w.status
|
||||
}
|
||||
|
||||
func (w *loggingResponseWriter) Size() int {
|
||||
return w.size
|
||||
}
|
||||
|
||||
func (w *loggingResponseWriter) ElapsedTime() string {
|
||||
return time.Since(w.start).String()
|
||||
}
|
||||
|
||||
func (w *loggingResponseWriter) Write(data []byte) (int, error) {
|
||||
size, err := w.ResponseWriter.Write(data)
|
||||
w.size += size
|
||||
return size, err
|
||||
}
|
||||
|
||||
func (w *loggingResponseWriter) WriteHeader(statusCode int) {
|
||||
w.status = statusCode
|
||||
w.ResponseWriter.WriteHeader(statusCode)
|
||||
}
|
||||
|
||||
func middleware(r *mux.Router) *mux.Router {
|
||||
r.Use(loggingMw)
|
||||
r.Use(discworldMw)
|
||||
log.Info("using")
|
||||
return r
|
||||
}
|
||||
|
||||
func discworldMw(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Clacks-Overhead", "GNU Terry Pratchett")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func loggingMw(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
newW := newLoggingResponseWriter(w)
|
||||
correlationID := CorrelationIDFromRequest(r)
|
||||
if correlationID == "" {
|
||||
correlationID = uuid.New().String()
|
||||
}
|
||||
requestID := uuid.New().String()
|
||||
contextLogger := log.WithFields(log.Fields{
|
||||
"requestID": requestID,
|
||||
"correlationID": correlationID,
|
||||
})
|
||||
ctx := r.Context()
|
||||
ctx = context.WithValue(ctx, requestIDKey, requestID)
|
||||
ctx = context.WithValue(ctx, correlationIDKey, correlationID)
|
||||
ctx = context.WithValue(ctx, loggerKey, contextLogger)
|
||||
r = r.WithContext(ctx)
|
||||
w.Header().Set(CorrelationIDHeader, correlationID)
|
||||
w.Header().Set(RequestIDHeader, requestID)
|
||||
requestLogger := contextLogger.WithFields(
|
||||
log.Fields{
|
||||
"path": r.URL.Path,
|
||||
"query_string": r.URL.RawQuery,
|
||||
"method": r.Method,
|
||||
})
|
||||
requestLogger.Info("Start web request")
|
||||
next.ServeHTTP(newW, r)
|
||||
requestLogger.WithFields(
|
||||
log.Fields{
|
||||
"status": newW.Status(),
|
||||
"size": newW.Size(),
|
||||
"duration": newW.ElapsedTime()}).
|
||||
Info("End web request")
|
||||
})
|
||||
}
|
||||
35
web/router.go
Normal file
35
web/router.go
Normal file
@ -0,0 +1,35 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func router() *mux.Router {
|
||||
r := mux.NewRouter()
|
||||
r.HandleFunc("/", root)
|
||||
return r
|
||||
}
|
||||
|
||||
func root(resp http.ResponseWriter, req *http.Request) {
|
||||
logger := LoggerFromContext(req.Context())
|
||||
if req.URL.Path != "/" {
|
||||
http.NotFound(resp, req)
|
||||
logger.Warning("404 Not found")
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(resp, "Hello World!")
|
||||
logger.Info("root page")
|
||||
}
|
||||
|
||||
// RunServer runs the webserver with the router and middleware
|
||||
func RunServer() {
|
||||
router := middleware(router())
|
||||
addr := viper.GetString("addr")
|
||||
log.WithFields(log.Fields{"addr": addr}).Info("Webserver starting")
|
||||
log.Fatal(http.ListenAndServe(viper.GetString("addr"), router))
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user