repo
stringlengths 5
67
| path
stringlengths 4
218
| func_name
stringlengths 0
151
| original_string
stringlengths 52
373k
| language
stringclasses 6
values | code
stringlengths 52
373k
| code_tokens
listlengths 10
512
| docstring
stringlengths 3
47.2k
| docstring_tokens
listlengths 3
234
| sha
stringlengths 40
40
| url
stringlengths 85
339
| partition
stringclasses 3
values |
|---|---|---|---|---|---|---|---|---|---|---|---|
sclevine/agouti
|
selection_properties.go
|
Attribute
|
func (s *Selection) Attribute(attribute string) (string, error) {
return s.hasProperty(element.Element.GetAttribute, attribute, "attribute")
}
|
go
|
func (s *Selection) Attribute(attribute string) (string, error) {
return s.hasProperty(element.Element.GetAttribute, attribute, "attribute")
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"Attribute",
"(",
"attribute",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"s",
".",
"hasProperty",
"(",
"element",
".",
"Element",
".",
"GetAttribute",
",",
"attribute",
",",
"\"attribute\"",
")",
"\n",
"}"
] |
// Attribute returns an attribute value for exactly one element.
|
[
"Attribute",
"returns",
"an",
"attribute",
"value",
"for",
"exactly",
"one",
"element",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L59-L61
|
test
|
sclevine/agouti
|
selection_properties.go
|
CSS
|
func (s *Selection) CSS(property string) (string, error) {
return s.hasProperty(element.Element.GetCSS, property, "CSS property")
}
|
go
|
func (s *Selection) CSS(property string) (string, error) {
return s.hasProperty(element.Element.GetCSS, property, "CSS property")
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"CSS",
"(",
"property",
"string",
")",
"(",
"string",
",",
"error",
")",
"{",
"return",
"s",
".",
"hasProperty",
"(",
"element",
".",
"Element",
".",
"GetCSS",
",",
"property",
",",
"\"CSS property\"",
")",
"\n",
"}"
] |
// CSS returns a CSS style property value for exactly one element.
|
[
"CSS",
"returns",
"a",
"CSS",
"style",
"property",
"value",
"for",
"exactly",
"one",
"element",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L64-L66
|
test
|
sclevine/agouti
|
selection_properties.go
|
Selected
|
func (s *Selection) Selected() (bool, error) {
return s.hasState(element.Element.IsSelected, "selected")
}
|
go
|
func (s *Selection) Selected() (bool, error) {
return s.hasState(element.Element.IsSelected, "selected")
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"Selected",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"s",
".",
"hasState",
"(",
"element",
".",
"Element",
".",
"IsSelected",
",",
"\"selected\"",
")",
"\n",
"}"
] |
// Selected returns true if all of the elements that the selection refers to are selected.
|
[
"Selected",
"returns",
"true",
"if",
"all",
"of",
"the",
"elements",
"that",
"the",
"selection",
"refers",
"to",
"are",
"selected",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L90-L92
|
test
|
sclevine/agouti
|
selection_properties.go
|
Visible
|
func (s *Selection) Visible() (bool, error) {
return s.hasState(element.Element.IsDisplayed, "visible")
}
|
go
|
func (s *Selection) Visible() (bool, error) {
return s.hasState(element.Element.IsDisplayed, "visible")
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"Visible",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"s",
".",
"hasState",
"(",
"element",
".",
"Element",
".",
"IsDisplayed",
",",
"\"visible\"",
")",
"\n",
"}"
] |
// Visible returns true if all of the elements that the selection refers to are visible.
|
[
"Visible",
"returns",
"true",
"if",
"all",
"of",
"the",
"elements",
"that",
"the",
"selection",
"refers",
"to",
"are",
"visible",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L95-L97
|
test
|
sclevine/agouti
|
selection_properties.go
|
Enabled
|
func (s *Selection) Enabled() (bool, error) {
return s.hasState(element.Element.IsEnabled, "enabled")
}
|
go
|
func (s *Selection) Enabled() (bool, error) {
return s.hasState(element.Element.IsEnabled, "enabled")
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"Enabled",
"(",
")",
"(",
"bool",
",",
"error",
")",
"{",
"return",
"s",
".",
"hasState",
"(",
"element",
".",
"Element",
".",
"IsEnabled",
",",
"\"enabled\"",
")",
"\n",
"}"
] |
// Enabled returns true if all of the elements that the selection refers to are enabled.
|
[
"Enabled",
"returns",
"true",
"if",
"all",
"of",
"the",
"elements",
"that",
"the",
"selection",
"refers",
"to",
"are",
"enabled",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_properties.go#L100-L102
|
test
|
sclevine/agouti
|
matchers/selection_matchers.go
|
HaveCount
|
func HaveCount(count int) types.GomegaMatcher {
return &internal.ValueMatcher{Method: "Count", Property: "element count", Expected: count}
}
|
go
|
func HaveCount(count int) types.GomegaMatcher {
return &internal.ValueMatcher{Method: "Count", Property: "element count", Expected: count}
}
|
[
"func",
"HaveCount",
"(",
"count",
"int",
")",
"types",
".",
"GomegaMatcher",
"{",
"return",
"&",
"internal",
".",
"ValueMatcher",
"{",
"Method",
":",
"\"Count\"",
",",
"Property",
":",
"\"element count\"",
",",
"Expected",
":",
"count",
"}",
"\n",
"}"
] |
// HaveCount passes when the expected element count is equal to the actual
// number of elements in the selection.
|
[
"HaveCount",
"passes",
"when",
"the",
"expected",
"element",
"count",
"is",
"equal",
"to",
"the",
"actual",
"number",
"of",
"elements",
"in",
"the",
"selection",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/selection_matchers.go#L22-L24
|
test
|
sclevine/agouti
|
matchers/selection_matchers.go
|
HaveAttribute
|
func HaveAttribute(attribute string, value string) types.GomegaMatcher {
return &internal.HaveAttributeMatcher{ExpectedAttribute: attribute, ExpectedValue: value}
}
|
go
|
func HaveAttribute(attribute string, value string) types.GomegaMatcher {
return &internal.HaveAttributeMatcher{ExpectedAttribute: attribute, ExpectedValue: value}
}
|
[
"func",
"HaveAttribute",
"(",
"attribute",
"string",
",",
"value",
"string",
")",
"types",
".",
"GomegaMatcher",
"{",
"return",
"&",
"internal",
".",
"HaveAttributeMatcher",
"{",
"ExpectedAttribute",
":",
"attribute",
",",
"ExpectedValue",
":",
"value",
"}",
"\n",
"}"
] |
// HaveAttribute passes when the expected attribute and value are present on the element.
// This matcher will fail if the provided selection refers to more than one element.
|
[
"HaveAttribute",
"passes",
"when",
"the",
"expected",
"attribute",
"and",
"value",
"are",
"present",
"on",
"the",
"element",
".",
"This",
"matcher",
"will",
"fail",
"if",
"the",
"provided",
"selection",
"refers",
"to",
"more",
"than",
"one",
"element",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/matchers/selection_matchers.go#L28-L30
|
test
|
sclevine/agouti
|
agouti.go
|
EdgeDriver
|
func EdgeDriver(options ...Option) *WebDriver {
var binaryName string
if runtime.GOOS == "windows" {
binaryName = "MicrosoftWebDriver.exe"
} else {
return nil
}
command := []string{binaryName, "--port={{.Port}}"}
// Using {{.Address}} means using 127.0.0.1
// But MicrosoftWebDriver only supports localhost, not 127.0.0.1
return NewWebDriver("http://localhost:{{.Port}}", command, options...)
}
|
go
|
func EdgeDriver(options ...Option) *WebDriver {
var binaryName string
if runtime.GOOS == "windows" {
binaryName = "MicrosoftWebDriver.exe"
} else {
return nil
}
command := []string{binaryName, "--port={{.Port}}"}
// Using {{.Address}} means using 127.0.0.1
// But MicrosoftWebDriver only supports localhost, not 127.0.0.1
return NewWebDriver("http://localhost:{{.Port}}", command, options...)
}
|
[
"func",
"EdgeDriver",
"(",
"options",
"...",
"Option",
")",
"*",
"WebDriver",
"{",
"var",
"binaryName",
"string",
"\n",
"if",
"runtime",
".",
"GOOS",
"==",
"\"windows\"",
"{",
"binaryName",
"=",
"\"MicrosoftWebDriver.exe\"",
"\n",
"}",
"else",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"command",
":=",
"[",
"]",
"string",
"{",
"binaryName",
",",
"\"--port={{.Port}}\"",
"}",
"\n",
"return",
"NewWebDriver",
"(",
"\"http://localhost:{{.Port}}\"",
",",
"command",
",",
"options",
"...",
")",
"\n",
"}"
] |
// EdgeDriver returns an instance of a EdgeDriver WebDriver.
//
// Provided Options will apply as default arguments for new pages.
// New pages will accept invalid SSL certificates by default. This
// may be disabled using the RejectInvalidSSL Option.
|
[
"EdgeDriver",
"returns",
"an",
"instance",
"of",
"a",
"EdgeDriver",
"WebDriver",
".",
"Provided",
"Options",
"will",
"apply",
"as",
"default",
"arguments",
"for",
"new",
"pages",
".",
"New",
"pages",
"will",
"accept",
"invalid",
"SSL",
"certificates",
"by",
"default",
".",
"This",
"may",
"be",
"disabled",
"using",
"the",
"RejectInvalidSSL",
"Option",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/agouti.go#L51-L62
|
test
|
sclevine/agouti
|
agouti.go
|
Selendroid
|
func Selendroid(jarFile string, options ...Option) *WebDriver {
absJARPath, err := filepath.Abs(jarFile)
if err != nil {
return nil
}
command := []string{
"java",
"-jar", absJARPath,
"-port", "{{.Port}}",
}
options = append([]Option{Timeout(90), Browser("android")}, options...)
return NewWebDriver("http://{{.Address}}/wd/hub", command, options...)
}
|
go
|
func Selendroid(jarFile string, options ...Option) *WebDriver {
absJARPath, err := filepath.Abs(jarFile)
if err != nil {
return nil
}
command := []string{
"java",
"-jar", absJARPath,
"-port", "{{.Port}}",
}
options = append([]Option{Timeout(90), Browser("android")}, options...)
return NewWebDriver("http://{{.Address}}/wd/hub", command, options...)
}
|
[
"func",
"Selendroid",
"(",
"jarFile",
"string",
",",
"options",
"...",
"Option",
")",
"*",
"WebDriver",
"{",
"absJARPath",
",",
"err",
":=",
"filepath",
".",
"Abs",
"(",
"jarFile",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"command",
":=",
"[",
"]",
"string",
"{",
"\"java\"",
",",
"\"-jar\"",
",",
"absJARPath",
",",
"\"-port\"",
",",
"\"{{.Port}}\"",
",",
"}",
"\n",
"options",
"=",
"append",
"(",
"[",
"]",
"Option",
"{",
"Timeout",
"(",
"90",
")",
",",
"Browser",
"(",
"\"android\"",
")",
"}",
",",
"options",
"...",
")",
"\n",
"return",
"NewWebDriver",
"(",
"\"http://{{.Address}}/wd/hub\"",
",",
"command",
",",
"options",
"...",
")",
"\n",
"}"
] |
// Selendroid returns an instance of a Selendroid WebDriver.
//
// Provided Options will apply as default arguments for new pages.
// New pages will accept invalid SSL certificates by default. This
// may be disabled using the RejectInvalidSSL Option.
//
// The jarFile is a relative or absolute path to Selendroid JAR file.
// Selendroid will return nil if an invalid path is provided.
|
[
"Selendroid",
"returns",
"an",
"instance",
"of",
"a",
"Selendroid",
"WebDriver",
".",
"Provided",
"Options",
"will",
"apply",
"as",
"default",
"arguments",
"for",
"new",
"pages",
".",
"New",
"pages",
"will",
"accept",
"invalid",
"SSL",
"certificates",
"by",
"default",
".",
"This",
"may",
"be",
"disabled",
"using",
"the",
"RejectInvalidSSL",
"Option",
".",
"The",
"jarFile",
"is",
"a",
"relative",
"or",
"absolute",
"path",
"to",
"Selendroid",
"JAR",
"file",
".",
"Selendroid",
"will",
"return",
"nil",
"if",
"an",
"invalid",
"path",
"is",
"provided",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/agouti.go#L82-L95
|
test
|
sclevine/agouti
|
selection_frames.go
|
SwitchToFrame
|
func (s *Selection) SwitchToFrame() error {
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return fmt.Errorf("failed to select element from %s: %s", s, err)
}
if err := s.session.Frame(selectedElement.(*api.Element)); err != nil {
return fmt.Errorf("failed to switch to frame referred to by %s: %s", s, err)
}
return nil
}
|
go
|
func (s *Selection) SwitchToFrame() error {
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return fmt.Errorf("failed to select element from %s: %s", s, err)
}
if err := s.session.Frame(selectedElement.(*api.Element)); err != nil {
return fmt.Errorf("failed to switch to frame referred to by %s: %s", s, err)
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"SwitchToFrame",
"(",
")",
"error",
"{",
"selectedElement",
",",
"err",
":=",
"s",
".",
"elements",
".",
"GetExactlyOne",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to select element from %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"session",
".",
"Frame",
"(",
"selectedElement",
".",
"(",
"*",
"api",
".",
"Element",
")",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to switch to frame referred to by %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// SwitchToFrame focuses on the frame specified by the selection. All new and
// existing selections will refer to the new frame. All further Page methods
// will apply to this frame as well.
|
[
"SwitchToFrame",
"focuses",
"on",
"the",
"frame",
"specified",
"by",
"the",
"selection",
".",
"All",
"new",
"and",
"existing",
"selections",
"will",
"refer",
"to",
"the",
"new",
"frame",
".",
"All",
"further",
"Page",
"methods",
"will",
"apply",
"to",
"this",
"frame",
"as",
"well",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection_frames.go#L12-L22
|
test
|
sclevine/agouti
|
selection.go
|
Count
|
func (s *Selection) Count() (int, error) {
elements, err := s.elements.Get()
if err != nil {
return 0, fmt.Errorf("failed to select elements from %s: %s", s, err)
}
return len(elements), nil
}
|
go
|
func (s *Selection) Count() (int, error) {
elements, err := s.elements.Get()
if err != nil {
return 0, fmt.Errorf("failed to select elements from %s: %s", s, err)
}
return len(elements), nil
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"Count",
"(",
")",
"(",
"int",
",",
"error",
")",
"{",
"elements",
",",
"err",
":=",
"s",
".",
"elements",
".",
"Get",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to select elements from %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"len",
"(",
"elements",
")",
",",
"nil",
"\n",
"}"
] |
// Count returns the number of elements that the selection refers to.
|
[
"Count",
"returns",
"the",
"number",
"of",
"elements",
"that",
"the",
"selection",
"refers",
"to",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L66-L73
|
test
|
sclevine/agouti
|
selection.go
|
EqualsElement
|
func (s *Selection) EqualsElement(other interface{}) (bool, error) {
otherSelection, ok := other.(*Selection)
if !ok {
multiSelection, ok := other.(*MultiSelection)
if !ok {
return false, fmt.Errorf("must be *Selection or *MultiSelection")
}
otherSelection = &multiSelection.Selection
}
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", s, err)
}
otherElement, err := otherSelection.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", other, err)
}
equal, err := selectedElement.IsEqualTo(otherElement.(*api.Element))
if err != nil {
return false, fmt.Errorf("failed to compare %s to %s: %s", s, other, err)
}
return equal, nil
}
|
go
|
func (s *Selection) EqualsElement(other interface{}) (bool, error) {
otherSelection, ok := other.(*Selection)
if !ok {
multiSelection, ok := other.(*MultiSelection)
if !ok {
return false, fmt.Errorf("must be *Selection or *MultiSelection")
}
otherSelection = &multiSelection.Selection
}
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", s, err)
}
otherElement, err := otherSelection.elements.GetExactlyOne()
if err != nil {
return false, fmt.Errorf("failed to select element from %s: %s", other, err)
}
equal, err := selectedElement.IsEqualTo(otherElement.(*api.Element))
if err != nil {
return false, fmt.Errorf("failed to compare %s to %s: %s", s, other, err)
}
return equal, nil
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"EqualsElement",
"(",
"other",
"interface",
"{",
"}",
")",
"(",
"bool",
",",
"error",
")",
"{",
"otherSelection",
",",
"ok",
":=",
"other",
".",
"(",
"*",
"Selection",
")",
"\n",
"if",
"!",
"ok",
"{",
"multiSelection",
",",
"ok",
":=",
"other",
".",
"(",
"*",
"MultiSelection",
")",
"\n",
"if",
"!",
"ok",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"must be *Selection or *MultiSelection\"",
")",
"\n",
"}",
"\n",
"otherSelection",
"=",
"&",
"multiSelection",
".",
"Selection",
"\n",
"}",
"\n",
"selectedElement",
",",
"err",
":=",
"s",
".",
"elements",
".",
"GetExactlyOne",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to select element from %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"otherElement",
",",
"err",
":=",
"otherSelection",
".",
"elements",
".",
"GetExactlyOne",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to select element from %s: %s\"",
",",
"other",
",",
"err",
")",
"\n",
"}",
"\n",
"equal",
",",
"err",
":=",
"selectedElement",
".",
"IsEqualTo",
"(",
"otherElement",
".",
"(",
"*",
"api",
".",
"Element",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
",",
"fmt",
".",
"Errorf",
"(",
"\"failed to compare %s to %s: %s\"",
",",
"s",
",",
"other",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"equal",
",",
"nil",
"\n",
"}"
] |
// EqualsElement returns whether or not two selections of exactly
// one element refer to the same element.
|
[
"EqualsElement",
"returns",
"whether",
"or",
"not",
"two",
"selections",
"of",
"exactly",
"one",
"element",
"refer",
"to",
"the",
"same",
"element",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L77-L103
|
test
|
sclevine/agouti
|
selection.go
|
MouseToElement
|
func (s *Selection) MouseToElement() error {
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return fmt.Errorf("failed to select element from %s: %s", s, err)
}
if err := s.session.MoveTo(selectedElement.(*api.Element), nil); err != nil {
return fmt.Errorf("failed to move mouse to element for %s: %s", s, err)
}
return nil
}
|
go
|
func (s *Selection) MouseToElement() error {
selectedElement, err := s.elements.GetExactlyOne()
if err != nil {
return fmt.Errorf("failed to select element from %s: %s", s, err)
}
if err := s.session.MoveTo(selectedElement.(*api.Element), nil); err != nil {
return fmt.Errorf("failed to move mouse to element for %s: %s", s, err)
}
return nil
}
|
[
"func",
"(",
"s",
"*",
"Selection",
")",
"MouseToElement",
"(",
")",
"error",
"{",
"selectedElement",
",",
"err",
":=",
"s",
".",
"elements",
".",
"GetExactlyOne",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to select element from %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"if",
"err",
":=",
"s",
".",
"session",
".",
"MoveTo",
"(",
"selectedElement",
".",
"(",
"*",
"api",
".",
"Element",
")",
",",
"nil",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"failed to move mouse to element for %s: %s\"",
",",
"s",
",",
"err",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// MouseToElement moves the mouse over exactly one element in the selection.
|
[
"MouseToElement",
"moves",
"the",
"mouse",
"over",
"exactly",
"one",
"element",
"in",
"the",
"selection",
"."
] |
96599c91888f1b1cf2dccc7f1776ba7f511909e5
|
https://github.com/sclevine/agouti/blob/96599c91888f1b1cf2dccc7f1776ba7f511909e5/selection.go#L106-L117
|
test
|
pact-foundation/pact-go
|
proxy/http.go
|
loggingMiddleware
|
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("[DEBUG] http reverse proxy received connection from %s on path %s\n", r.RemoteAddr, r.RequestURI)
next.ServeHTTP(w, r)
})
}
|
go
|
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("[DEBUG] http reverse proxy received connection from %s on path %s\n", r.RemoteAddr, r.RequestURI)
next.ServeHTTP(w, r)
})
}
|
[
"func",
"loggingMiddleware",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"log",
".",
"Printf",
"(",
"\"[DEBUG] http reverse proxy received connection from %s on path %s\\n\"",
",",
"\\n",
",",
"r",
".",
"RemoteAddr",
")",
"\n",
"r",
".",
"RequestURI",
"\n",
"}",
")",
"\n",
"}"
] |
// loggingMiddleware logs requests to the proxy
|
[
"loggingMiddleware",
"logs",
"requests",
"to",
"the",
"proxy"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/proxy/http.go#L37-L42
|
test
|
pact-foundation/pact-go
|
proxy/http.go
|
chainHandlers
|
func chainHandlers(mw ...Middleware) Middleware {
return func(final http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
last := final
for i := len(mw) - 1; i >= 0; i-- {
last = mw[i](last)
}
last.ServeHTTP(w, r)
})
}
}
|
go
|
func chainHandlers(mw ...Middleware) Middleware {
return func(final http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
last := final
for i := len(mw) - 1; i >= 0; i-- {
last = mw[i](last)
}
last.ServeHTTP(w, r)
})
}
}
|
[
"func",
"chainHandlers",
"(",
"mw",
"...",
"Middleware",
")",
"Middleware",
"{",
"return",
"func",
"(",
"final",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"last",
":=",
"final",
"\n",
"for",
"i",
":=",
"len",
"(",
"mw",
")",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
"{",
"last",
"=",
"mw",
"[",
"i",
"]",
"(",
"last",
")",
"\n",
"}",
"\n",
"last",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// chainHandlers takes a set of middleware and joins them together
// into a single Middleware, making it much simpler to compose middleware
// together
|
[
"chainHandlers",
"takes",
"a",
"set",
"of",
"middleware",
"and",
"joins",
"them",
"together",
"into",
"a",
"single",
"Middleware",
"making",
"it",
"much",
"simpler",
"to",
"compose",
"middleware",
"together"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/proxy/http.go#L47-L57
|
test
|
pact-foundation/pact-go
|
proxy/http.go
|
HTTPReverseProxy
|
func HTTPReverseProxy(options Options) (int, error) {
port := options.ProxyPort
var err error
proxy := httputil.NewSingleHostReverseProxy(&url.URL{
Scheme: options.TargetScheme,
Host: options.TargetAddress,
})
if port == 0 {
port, err = utils.GetFreePort()
if err != nil {
log.Println("[ERROR] unable to start reverse proxy server:", err)
return 0, err
}
}
wrapper := chainHandlers(append(options.Middleware, loggingMiddleware)...)
log.Println("[DEBUG] starting reverse proxy on port", port)
go http.ListenAndServe(fmt.Sprintf(":%d", port), wrapper(proxy))
return port, nil
}
|
go
|
func HTTPReverseProxy(options Options) (int, error) {
port := options.ProxyPort
var err error
proxy := httputil.NewSingleHostReverseProxy(&url.URL{
Scheme: options.TargetScheme,
Host: options.TargetAddress,
})
if port == 0 {
port, err = utils.GetFreePort()
if err != nil {
log.Println("[ERROR] unable to start reverse proxy server:", err)
return 0, err
}
}
wrapper := chainHandlers(append(options.Middleware, loggingMiddleware)...)
log.Println("[DEBUG] starting reverse proxy on port", port)
go http.ListenAndServe(fmt.Sprintf(":%d", port), wrapper(proxy))
return port, nil
}
|
[
"func",
"HTTPReverseProxy",
"(",
"options",
"Options",
")",
"(",
"int",
",",
"error",
")",
"{",
"port",
":=",
"options",
".",
"ProxyPort",
"\n",
"var",
"err",
"error",
"\n",
"proxy",
":=",
"httputil",
".",
"NewSingleHostReverseProxy",
"(",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"options",
".",
"TargetScheme",
",",
"Host",
":",
"options",
".",
"TargetAddress",
",",
"}",
")",
"\n",
"if",
"port",
"==",
"0",
"{",
"port",
",",
"err",
"=",
"utils",
".",
"GetFreePort",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"[ERROR] unable to start reverse proxy server:\"",
",",
"err",
")",
"\n",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"wrapper",
":=",
"chainHandlers",
"(",
"append",
"(",
"options",
".",
"Middleware",
",",
"loggingMiddleware",
")",
"...",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] starting reverse proxy on port\"",
",",
"port",
")",
"\n",
"go",
"http",
".",
"ListenAndServe",
"(",
"fmt",
".",
"Sprintf",
"(",
"\":%d\"",
",",
"port",
")",
",",
"wrapper",
"(",
"proxy",
")",
")",
"\n",
"return",
"port",
",",
"nil",
"\n",
"}"
] |
// HTTPReverseProxy provides a default setup for proxying
// internal components within the framework
|
[
"HTTPReverseProxy",
"provides",
"a",
"default",
"setup",
"for",
"proxying",
"internal",
"components",
"within",
"the",
"framework"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/proxy/http.go#L61-L84
|
test
|
pact-foundation/pact-go
|
install/installer.go
|
CheckInstallation
|
func (i *Installer) CheckInstallation() error {
for binary, versionRange := range versionMap {
log.Println("[INFO] checking", binary, "within range", versionRange)
version, err := i.GetVersionForBinary(binary)
if err != nil {
return err
}
if err = i.CheckVersion(binary, version); err != nil {
return err
}
}
return nil
}
|
go
|
func (i *Installer) CheckInstallation() error {
for binary, versionRange := range versionMap {
log.Println("[INFO] checking", binary, "within range", versionRange)
version, err := i.GetVersionForBinary(binary)
if err != nil {
return err
}
if err = i.CheckVersion(binary, version); err != nil {
return err
}
}
return nil
}
|
[
"func",
"(",
"i",
"*",
"Installer",
")",
"CheckInstallation",
"(",
")",
"error",
"{",
"for",
"binary",
",",
"versionRange",
":=",
"range",
"versionMap",
"{",
"log",
".",
"Println",
"(",
"\"[INFO] checking\"",
",",
"binary",
",",
"\"within range\"",
",",
"versionRange",
")",
"\n",
"version",
",",
"err",
":=",
"i",
".",
"GetVersionForBinary",
"(",
"binary",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"if",
"err",
"=",
"i",
".",
"CheckVersion",
"(",
"binary",
",",
"version",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CheckInstallation checks installation of all of the tools
|
[
"CheckInstallation",
"checks",
"installation",
"of",
"all",
"of",
"the",
"tools"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/install/installer.go#L37-L53
|
test
|
pact-foundation/pact-go
|
install/installer.go
|
CheckVersion
|
func (i *Installer) CheckVersion(binary, version string) error {
log.Println("[DEBUG] checking version for binary", binary, "version", version)
v, err := goversion.NewVersion(version)
if err != nil {
log.Println("[DEBUG] err", err)
return err
}
versionRange, ok := versionMap[binary]
if !ok {
return fmt.Errorf("unable to find version range for binary %s", binary)
}
log.Println("[DEBUG] checking if version", v, "within semver range", versionRange)
constraints, err := goversion.NewConstraint(versionRange)
if constraints.Check(v) {
log.Println("[DEBUG]", v, "satisfies constraints", v, constraints)
return nil
}
return fmt.Errorf("version %s of %s does not match constraint %s", version, binary, versionRange)
}
|
go
|
func (i *Installer) CheckVersion(binary, version string) error {
log.Println("[DEBUG] checking version for binary", binary, "version", version)
v, err := goversion.NewVersion(version)
if err != nil {
log.Println("[DEBUG] err", err)
return err
}
versionRange, ok := versionMap[binary]
if !ok {
return fmt.Errorf("unable to find version range for binary %s", binary)
}
log.Println("[DEBUG] checking if version", v, "within semver range", versionRange)
constraints, err := goversion.NewConstraint(versionRange)
if constraints.Check(v) {
log.Println("[DEBUG]", v, "satisfies constraints", v, constraints)
return nil
}
return fmt.Errorf("version %s of %s does not match constraint %s", version, binary, versionRange)
}
|
[
"func",
"(",
"i",
"*",
"Installer",
")",
"CheckVersion",
"(",
"binary",
",",
"version",
"string",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] checking version for binary\"",
",",
"binary",
",",
"\"version\"",
",",
"version",
")",
"\n",
"v",
",",
"err",
":=",
"goversion",
".",
"NewVersion",
"(",
"version",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] err\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"versionRange",
",",
"ok",
":=",
"versionMap",
"[",
"binary",
"]",
"\n",
"if",
"!",
"ok",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unable to find version range for binary %s\"",
",",
"binary",
")",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] checking if version\"",
",",
"v",
",",
"\"within semver range\"",
",",
"versionRange",
")",
"\n",
"constraints",
",",
"err",
":=",
"goversion",
".",
"NewConstraint",
"(",
"versionRange",
")",
"\n",
"if",
"constraints",
".",
"Check",
"(",
"v",
")",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG]\"",
",",
"v",
",",
"\"satisfies constraints\"",
",",
"v",
",",
"constraints",
")",
"\n",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"version %s of %s does not match constraint %s\"",
",",
"version",
",",
"binary",
",",
"versionRange",
")",
"\n",
"}"
] |
// CheckVersion checks installation of a given binary using semver-compatible
// comparisions
|
[
"CheckVersion",
"checks",
"installation",
"of",
"a",
"given",
"binary",
"using",
"semver",
"-",
"compatible",
"comparisions"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/install/installer.go#L57-L78
|
test
|
pact-foundation/pact-go
|
install/installer.go
|
GetVersionForBinary
|
func (i *Installer) GetVersionForBinary(binary string) (version string, err error) {
log.Println("[DEBUG] running binary", binary)
content, err := i.commander.Output(binary, "version")
elements := strings.Split(strings.TrimSpace(string(content)), "\n")
version = strings.TrimSpace(elements[len(elements)-1])
return version, err
}
|
go
|
func (i *Installer) GetVersionForBinary(binary string) (version string, err error) {
log.Println("[DEBUG] running binary", binary)
content, err := i.commander.Output(binary, "version")
elements := strings.Split(strings.TrimSpace(string(content)), "\n")
version = strings.TrimSpace(elements[len(elements)-1])
return version, err
}
|
[
"func",
"(",
"i",
"*",
"Installer",
")",
"GetVersionForBinary",
"(",
"binary",
"string",
")",
"(",
"version",
"string",
",",
"err",
"error",
")",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] running binary\"",
",",
"binary",
")",
"\n",
"content",
",",
"err",
":=",
"i",
".",
"commander",
".",
"Output",
"(",
"binary",
",",
"\"version\"",
")",
"\n",
"elements",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"content",
")",
")",
",",
"\"\\n\"",
")",
"\n",
"\\n",
"\n",
"version",
"=",
"strings",
".",
"TrimSpace",
"(",
"elements",
"[",
"len",
"(",
"elements",
")",
"-",
"1",
"]",
")",
"\n",
"}"
] |
// GetVersionForBinary gets the version of a given Ruby binary
|
[
"GetVersionForBinary",
"gets",
"the",
"version",
"of",
"a",
"given",
"Ruby",
"binary"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/install/installer.go#L81-L89
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
getUser
|
func (c *Client) getUser(id string) (*ex.User, error) {
u := fmt.Sprintf("%s/users/%s", c.Host, id)
req, err := http.NewRequest("GET", u, nil)
// NOTE: by default, request bodies are expected to be sent with a Content-Type
// of application/json. If you don't explicitly set the content-type, you
// will get a mismatch during Verification.
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.token)
res, err := http.DefaultClient.Do(req)
if res.StatusCode != 200 || err != nil {
return nil, fmt.Errorf("get user failed")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var response ex.User
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return &response, err
}
|
go
|
func (c *Client) getUser(id string) (*ex.User, error) {
u := fmt.Sprintf("%s/users/%s", c.Host, id)
req, err := http.NewRequest("GET", u, nil)
// NOTE: by default, request bodies are expected to be sent with a Content-Type
// of application/json. If you don't explicitly set the content-type, you
// will get a mismatch during Verification.
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", c.token)
res, err := http.DefaultClient.Do(req)
if res.StatusCode != 200 || err != nil {
return nil, fmt.Errorf("get user failed")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var response ex.User
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return &response, err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"getUser",
"(",
"id",
"string",
")",
"(",
"*",
"ex",
".",
"User",
",",
"error",
")",
"{",
"u",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/users/%s\"",
",",
"c",
".",
"Host",
",",
"id",
")",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"GET\"",
",",
"u",
",",
"nil",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"Authorization\"",
",",
"c",
".",
"token",
")",
"\n",
"res",
",",
"err",
":=",
"http",
".",
"DefaultClient",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"!=",
"200",
"||",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"get user failed\"",
")",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"response",
"ex",
".",
"User",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"response",
",",
"err",
"\n",
"}"
] |
// getUser finds a user
|
[
"getUser",
"finds",
"a",
"user"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L36-L65
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
login
|
func (c *Client) login(username string, password string) (*ex.User, error) {
loginRequest := fmt.Sprintf(`
{
"username":"%s",
"password": "%s"
}`, username, password)
res, err := http.Post(fmt.Sprintf("%s/login/10?foo=anything", c.Host), "application/json; charset=utf-8", bytes.NewReader([]byte(loginRequest)))
if res.StatusCode != 200 || err != nil {
return nil, fmt.Errorf("login failed")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var response loginResponse
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return &response.User, err
}
|
go
|
func (c *Client) login(username string, password string) (*ex.User, error) {
loginRequest := fmt.Sprintf(`
{
"username":"%s",
"password": "%s"
}`, username, password)
res, err := http.Post(fmt.Sprintf("%s/login/10?foo=anything", c.Host), "application/json; charset=utf-8", bytes.NewReader([]byte(loginRequest)))
if res.StatusCode != 200 || err != nil {
return nil, fmt.Errorf("login failed")
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
var response loginResponse
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return &response.User, err
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"login",
"(",
"username",
"string",
",",
"password",
"string",
")",
"(",
"*",
"ex",
".",
"User",
",",
"error",
")",
"{",
"loginRequest",
":=",
"fmt",
".",
"Sprintf",
"(",
"` { \"username\":\"%s\", \"password\": \"%s\" }`",
",",
"username",
",",
"password",
")",
"\n",
"res",
",",
"err",
":=",
"http",
".",
"Post",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s/login/10?foo=anything\"",
",",
"c",
".",
"Host",
")",
",",
"\"application/json; charset=utf-8\"",
",",
"bytes",
".",
"NewReader",
"(",
"[",
"]",
"byte",
"(",
"loginRequest",
")",
")",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"!=",
"200",
"||",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"fmt",
".",
"Errorf",
"(",
"\"login failed\"",
")",
"\n",
"}",
"\n",
"data",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"response",
"loginResponse",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"data",
",",
"&",
"response",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"&",
"response",
".",
"User",
",",
"err",
"\n",
"}"
] |
// Login handles the login API call to the User Service.
|
[
"Login",
"handles",
"the",
"login",
"API",
"call",
"to",
"the",
"User",
"Service",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L68-L92
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
loginHandler
|
func (c *Client) loginHandler(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
user, err := c.login(username, password)
if err == nil && user != nil {
c.user = user
c.err = nil
http.Redirect(w, r, "/", http.StatusFound)
return
}
c.err = fmt.Errorf("Invalid username/password")
http.Redirect(w, r, "/", http.StatusFound)
return
}
|
go
|
func (c *Client) loginHandler(w http.ResponseWriter, r *http.Request) {
username := r.FormValue("username")
password := r.FormValue("password")
user, err := c.login(username, password)
if err == nil && user != nil {
c.user = user
c.err = nil
http.Redirect(w, r, "/", http.StatusFound)
return
}
c.err = fmt.Errorf("Invalid username/password")
http.Redirect(w, r, "/", http.StatusFound)
return
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"loginHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"username",
":=",
"r",
".",
"FormValue",
"(",
"\"username\"",
")",
"\n",
"password",
":=",
"r",
".",
"FormValue",
"(",
"\"password\"",
")",
"\n",
"user",
",",
"err",
":=",
"c",
".",
"login",
"(",
"username",
",",
"password",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"user",
"!=",
"nil",
"{",
"c",
".",
"user",
"=",
"user",
"\n",
"c",
".",
"err",
"=",
"nil",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"\"/\"",
",",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"\n",
"}",
"\n",
"c",
".",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"Invalid username/password\"",
")",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"\"/\"",
",",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"\n",
"}"
] |
// Deal with the login request.
|
[
"Deal",
"with",
"the",
"login",
"request",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L95-L109
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
logoutHandler
|
func (c *Client) logoutHandler(w http.ResponseWriter, r *http.Request) {
c.user = nil
c.err = nil
http.Redirect(w, r, "/", http.StatusFound)
return
}
|
go
|
func (c *Client) logoutHandler(w http.ResponseWriter, r *http.Request) {
c.user = nil
c.err = nil
http.Redirect(w, r, "/", http.StatusFound)
return
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"logoutHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"c",
".",
"user",
"=",
"nil",
"\n",
"c",
".",
"err",
"=",
"nil",
"\n",
"http",
".",
"Redirect",
"(",
"w",
",",
"r",
",",
"\"/\"",
",",
"http",
".",
"StatusFound",
")",
"\n",
"return",
"\n",
"}"
] |
// Deal with the logout request.
|
[
"Deal",
"with",
"the",
"logout",
"request",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L112-L117
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
viewHandler
|
func (c *Client) viewHandler(w http.ResponseWriter, r *http.Request) {
data := templateData{
User: c.user,
Error: c.err,
}
renderTemplate(w, "login", data)
}
|
go
|
func (c *Client) viewHandler(w http.ResponseWriter, r *http.Request) {
data := templateData{
User: c.user,
Error: c.err,
}
renderTemplate(w, "login", data)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"viewHandler",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"data",
":=",
"templateData",
"{",
"User",
":",
"c",
".",
"user",
",",
"Error",
":",
"c",
".",
"err",
",",
"}",
"\n",
"renderTemplate",
"(",
"w",
",",
"\"login\"",
",",
"data",
")",
"\n",
"}"
] |
// Show the current user if logged in, otherwise display a login form.
|
[
"Show",
"the",
"current",
"user",
"if",
"logged",
"in",
"otherwise",
"display",
"a",
"login",
"form",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L128-L134
|
test
|
pact-foundation/pact-go
|
examples/consumer/goconsumer/client.go
|
Run
|
func (c *Client) Run() {
http.HandleFunc("/login", c.loginHandler)
http.HandleFunc("/logout", c.logoutHandler)
http.HandleFunc("/", c.viewHandler)
fmt.Println("User svc client running on port 8081")
http.ListenAndServe(":8081", nil)
}
|
go
|
func (c *Client) Run() {
http.HandleFunc("/login", c.loginHandler)
http.HandleFunc("/logout", c.logoutHandler)
http.HandleFunc("/", c.viewHandler)
fmt.Println("User svc client running on port 8081")
http.ListenAndServe(":8081", nil)
}
|
[
"func",
"(",
"c",
"*",
"Client",
")",
"Run",
"(",
")",
"{",
"http",
".",
"HandleFunc",
"(",
"\"/login\"",
",",
"c",
".",
"loginHandler",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"/logout\"",
",",
"c",
".",
"logoutHandler",
")",
"\n",
"http",
".",
"HandleFunc",
"(",
"\"/\"",
",",
"c",
".",
"viewHandler",
")",
"\n",
"fmt",
".",
"Println",
"(",
"\"User svc client running on port 8081\"",
")",
"\n",
"http",
".",
"ListenAndServe",
"(",
"\":8081\"",
",",
"nil",
")",
"\n",
"}"
] |
// Run the web application.
|
[
"Run",
"the",
"web",
"application",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/consumer/goconsumer/client.go#L137-L143
|
test
|
pact-foundation/pact-go
|
dsl/interaction.go
|
WithRequest
|
func (i *Interaction) WithRequest(request Request) *Interaction {
i.Request = request
// Check if someone tried to add an object as a string representation
// as per original allowed implementation, e.g.
// { "foo": "bar", "baz": like("bat") }
if isJSONFormattedObject(request.Body) {
log.Println("[WARN] request body appears to be a JSON formatted object, " +
"no structural matching will occur. Support for structured strings has been" +
"deprecated as of 0.13.0")
}
return i
}
|
go
|
func (i *Interaction) WithRequest(request Request) *Interaction {
i.Request = request
// Check if someone tried to add an object as a string representation
// as per original allowed implementation, e.g.
// { "foo": "bar", "baz": like("bat") }
if isJSONFormattedObject(request.Body) {
log.Println("[WARN] request body appears to be a JSON formatted object, " +
"no structural matching will occur. Support for structured strings has been" +
"deprecated as of 0.13.0")
}
return i
}
|
[
"func",
"(",
"i",
"*",
"Interaction",
")",
"WithRequest",
"(",
"request",
"Request",
")",
"*",
"Interaction",
"{",
"i",
".",
"Request",
"=",
"request",
"\n",
"if",
"isJSONFormattedObject",
"(",
"request",
".",
"Body",
")",
"{",
"log",
".",
"Println",
"(",
"\"[WARN] request body appears to be a JSON formatted object, \"",
"+",
"\"no structural matching will occur. Support for structured strings has been\"",
"+",
"\"deprecated as of 0.13.0\"",
")",
"\n",
"}",
"\n",
"return",
"i",
"\n",
"}"
] |
// WithRequest specifies the details of the HTTP request that will be used to
// confirm that the Provider provides an API listening on the given interface.
// Mandatory.
|
[
"WithRequest",
"specifies",
"the",
"details",
"of",
"the",
"HTTP",
"request",
"that",
"will",
"be",
"used",
"to",
"confirm",
"that",
"the",
"Provider",
"provides",
"an",
"API",
"listening",
"on",
"the",
"given",
"interface",
".",
"Mandatory",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/interaction.go#L41-L54
|
test
|
pact-foundation/pact-go
|
dsl/interaction.go
|
WillRespondWith
|
func (i *Interaction) WillRespondWith(response Response) *Interaction {
i.Response = response
return i
}
|
go
|
func (i *Interaction) WillRespondWith(response Response) *Interaction {
i.Response = response
return i
}
|
[
"func",
"(",
"i",
"*",
"Interaction",
")",
"WillRespondWith",
"(",
"response",
"Response",
")",
"*",
"Interaction",
"{",
"i",
".",
"Response",
"=",
"response",
"\n",
"return",
"i",
"\n",
"}"
] |
// WillRespondWith specifies the details of the HTTP response that will be used to
// confirm that the Provider must satisfy. Mandatory.
|
[
"WillRespondWith",
"specifies",
"the",
"details",
"of",
"the",
"HTTP",
"response",
"that",
"will",
"be",
"used",
"to",
"confirm",
"that",
"the",
"Provider",
"must",
"satisfy",
".",
"Mandatory",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/interaction.go#L58-L62
|
test
|
pact-foundation/pact-go
|
dsl/interaction.go
|
isJSONFormattedObject
|
func isJSONFormattedObject(stringOrObject interface{}) bool {
switch content := stringOrObject.(type) {
case []byte:
case string:
var obj interface{}
err := json.Unmarshal([]byte(content), &obj)
if err != nil {
return false
}
// Check if a map type
if _, ok := obj.(map[string]interface{}); ok {
return true
}
}
return false
}
|
go
|
func isJSONFormattedObject(stringOrObject interface{}) bool {
switch content := stringOrObject.(type) {
case []byte:
case string:
var obj interface{}
err := json.Unmarshal([]byte(content), &obj)
if err != nil {
return false
}
// Check if a map type
if _, ok := obj.(map[string]interface{}); ok {
return true
}
}
return false
}
|
[
"func",
"isJSONFormattedObject",
"(",
"stringOrObject",
"interface",
"{",
"}",
")",
"bool",
"{",
"switch",
"content",
":=",
"stringOrObject",
".",
"(",
"type",
")",
"{",
"case",
"[",
"]",
"byte",
":",
"case",
"string",
":",
"var",
"obj",
"interface",
"{",
"}",
"\n",
"err",
":=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"content",
")",
",",
"&",
"obj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"false",
"\n",
"}",
"\n",
"if",
"_",
",",
"ok",
":=",
"obj",
".",
"(",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
")",
";",
"ok",
"{",
"return",
"true",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"false",
"\n",
"}"
] |
// Checks to see if someone has tried to submit a JSON string
// for an object, which is no longer supported
|
[
"Checks",
"to",
"see",
"if",
"someone",
"has",
"tried",
"to",
"submit",
"a",
"JSON",
"string",
"for",
"an",
"object",
"which",
"is",
"no",
"longer",
"supported"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/interaction.go#L66-L84
|
test
|
pact-foundation/pact-go
|
examples/types/repository.go
|
ByUsername
|
func (u *UserRepository) ByUsername(username string) (*User, error) {
if user, ok := u.Users[username]; ok {
return user, nil
}
return nil, ErrNotFound
}
|
go
|
func (u *UserRepository) ByUsername(username string) (*User, error) {
if user, ok := u.Users[username]; ok {
return user, nil
}
return nil, ErrNotFound
}
|
[
"func",
"(",
"u",
"*",
"UserRepository",
")",
"ByUsername",
"(",
"username",
"string",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"if",
"user",
",",
"ok",
":=",
"u",
".",
"Users",
"[",
"username",
"]",
";",
"ok",
"{",
"return",
"user",
",",
"nil",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"}"
] |
// ByUsername finds a user by their username.
|
[
"ByUsername",
"finds",
"a",
"user",
"by",
"their",
"username",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/types/repository.go#L10-L15
|
test
|
pact-foundation/pact-go
|
examples/types/repository.go
|
ByID
|
func (u *UserRepository) ByID(ID int) (*User, error) {
for _, user := range u.Users {
if user.ID == ID {
return user, nil
}
}
return nil, ErrNotFound
}
|
go
|
func (u *UserRepository) ByID(ID int) (*User, error) {
for _, user := range u.Users {
if user.ID == ID {
return user, nil
}
}
return nil, ErrNotFound
}
|
[
"func",
"(",
"u",
"*",
"UserRepository",
")",
"ByID",
"(",
"ID",
"int",
")",
"(",
"*",
"User",
",",
"error",
")",
"{",
"for",
"_",
",",
"user",
":=",
"range",
"u",
".",
"Users",
"{",
"if",
"user",
".",
"ID",
"==",
"ID",
"{",
"return",
"user",
",",
"nil",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
",",
"ErrNotFound",
"\n",
"}"
] |
// ByID finds a user by their ID
|
[
"ByID",
"finds",
"a",
"user",
"by",
"their",
"ID"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/types/repository.go#L18-L25
|
test
|
pact-foundation/pact-go
|
examples/mux/provider/user_service.go
|
UserLogin
|
func UserLogin(w http.ResponseWriter, r *http.Request) {
var login types.LoginRequest
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Api-Correlation-Id", "1234")
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
err = json.Unmarshal(body, &login)
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
user, err := userRepository.ByUsername(login.Username)
if err != nil {
w.WriteHeader(http.StatusNotFound)
} else if user.Username != login.Username || user.Password != login.Password {
w.WriteHeader(http.StatusUnauthorized)
} else {
w.Header().Set("X-Auth-Token", getAuthToken())
w.WriteHeader(http.StatusOK)
res := types.LoginResponse{User: user}
resBody, _ := json.Marshal(res)
w.Write(resBody)
}
}
|
go
|
func UserLogin(w http.ResponseWriter, r *http.Request) {
var login types.LoginRequest
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Api-Correlation-Id", "1234")
body, err := ioutil.ReadAll(r.Body)
defer r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
err = json.Unmarshal(body, &login)
if err != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
user, err := userRepository.ByUsername(login.Username)
if err != nil {
w.WriteHeader(http.StatusNotFound)
} else if user.Username != login.Username || user.Password != login.Password {
w.WriteHeader(http.StatusUnauthorized)
} else {
w.Header().Set("X-Auth-Token", getAuthToken())
w.WriteHeader(http.StatusOK)
res := types.LoginResponse{User: user}
resBody, _ := json.Marshal(res)
w.Write(resBody)
}
}
|
[
"func",
"UserLogin",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"var",
"login",
"types",
".",
"LoginRequest",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json; charset=utf-8\"",
")",
"\n",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"X-Api-Correlation-Id\"",
",",
"\"1234\"",
")",
"\n",
"body",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"r",
".",
"Body",
")",
"\n",
"defer",
"r",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"body",
",",
"&",
"login",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusServiceUnavailable",
")",
"\n",
"return",
"\n",
"}",
"\n",
"user",
",",
"err",
":=",
"userRepository",
".",
"ByUsername",
"(",
"login",
".",
"Username",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusNotFound",
")",
"\n",
"}",
"else",
"if",
"user",
".",
"Username",
"!=",
"login",
".",
"Username",
"||",
"user",
".",
"Password",
"!=",
"login",
".",
"Password",
"{",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusUnauthorized",
")",
"\n",
"}",
"else",
"{",
"w",
".",
"Header",
"(",
")",
".",
"Set",
"(",
"\"X-Auth-Token\"",
",",
"getAuthToken",
"(",
")",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"res",
":=",
"types",
".",
"LoginResponse",
"{",
"User",
":",
"user",
"}",
"\n",
"resBody",
",",
"_",
":=",
"json",
".",
"Marshal",
"(",
"res",
")",
"\n",
"w",
".",
"Write",
"(",
"resBody",
")",
"\n",
"}",
"\n",
"}"
] |
// UserLogin logs a user in, returning an auth token and the user object
|
[
"UserLogin",
"logs",
"a",
"user",
"in",
"returning",
"an",
"auth",
"token",
"and",
"the",
"user",
"object"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/mux/provider/user_service.go#L45-L76
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
newClient
|
func newClient(MockServiceManager client.Service, verificationServiceManager client.Service, messageServiceManager client.Service, publishServiceManager client.Service) *PactClient {
MockServiceManager.Setup()
verificationServiceManager.Setup()
messageServiceManager.Setup()
publishServiceManager.Setup()
return &PactClient{
pactMockSvcManager: MockServiceManager,
verificationSvcManager: verificationServiceManager,
messageSvcManager: messageServiceManager,
publishSvcManager: publishServiceManager,
TimeoutDuration: 10 * time.Second,
}
}
|
go
|
func newClient(MockServiceManager client.Service, verificationServiceManager client.Service, messageServiceManager client.Service, publishServiceManager client.Service) *PactClient {
MockServiceManager.Setup()
verificationServiceManager.Setup()
messageServiceManager.Setup()
publishServiceManager.Setup()
return &PactClient{
pactMockSvcManager: MockServiceManager,
verificationSvcManager: verificationServiceManager,
messageSvcManager: messageServiceManager,
publishSvcManager: publishServiceManager,
TimeoutDuration: 10 * time.Second,
}
}
|
[
"func",
"newClient",
"(",
"MockServiceManager",
"client",
".",
"Service",
",",
"verificationServiceManager",
"client",
".",
"Service",
",",
"messageServiceManager",
"client",
".",
"Service",
",",
"publishServiceManager",
"client",
".",
"Service",
")",
"*",
"PactClient",
"{",
"MockServiceManager",
".",
"Setup",
"(",
")",
"\n",
"verificationServiceManager",
".",
"Setup",
"(",
")",
"\n",
"messageServiceManager",
".",
"Setup",
"(",
")",
"\n",
"publishServiceManager",
".",
"Setup",
"(",
")",
"\n",
"return",
"&",
"PactClient",
"{",
"pactMockSvcManager",
":",
"MockServiceManager",
",",
"verificationSvcManager",
":",
"verificationServiceManager",
",",
"messageSvcManager",
":",
"messageServiceManager",
",",
"publishSvcManager",
":",
"publishServiceManager",
",",
"TimeoutDuration",
":",
"10",
"*",
"time",
".",
"Second",
",",
"}",
"\n",
"}"
] |
// newClient creates a new Pact client manager with the provided services
|
[
"newClient",
"creates",
"a",
"new",
"Pact",
"client",
"manager",
"with",
"the",
"provided",
"services"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L71-L84
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
NewClient
|
func NewClient() *PactClient {
return newClient(&client.MockService{}, &client.VerificationService{}, &client.MessageService{}, &client.PublishService{})
}
|
go
|
func NewClient() *PactClient {
return newClient(&client.MockService{}, &client.VerificationService{}, &client.MessageService{}, &client.PublishService{})
}
|
[
"func",
"NewClient",
"(",
")",
"*",
"PactClient",
"{",
"return",
"newClient",
"(",
"&",
"client",
".",
"MockService",
"{",
"}",
",",
"&",
"client",
".",
"VerificationService",
"{",
"}",
",",
"&",
"client",
".",
"MessageService",
"{",
"}",
",",
"&",
"client",
".",
"PublishService",
"{",
"}",
")",
"\n",
"}"
] |
// NewClient creates a new Pact client manager with defaults
|
[
"NewClient",
"creates",
"a",
"new",
"Pact",
"client",
"manager",
"with",
"defaults"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L87-L89
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
ListServers
|
func (p *PactClient) ListServers() []*types.MockServer {
log.Println("[DEBUG] client: starting a server")
var servers []*types.MockServer
for port, s := range p.pactMockSvcManager.List() {
servers = append(servers, &types.MockServer{
Pid: s.Process.Pid,
Port: port,
})
}
return servers
}
|
go
|
func (p *PactClient) ListServers() []*types.MockServer {
log.Println("[DEBUG] client: starting a server")
var servers []*types.MockServer
for port, s := range p.pactMockSvcManager.List() {
servers = append(servers, &types.MockServer{
Pid: s.Process.Pid,
Port: port,
})
}
return servers
}
|
[
"func",
"(",
"p",
"*",
"PactClient",
")",
"ListServers",
"(",
")",
"[",
"]",
"*",
"types",
".",
"MockServer",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] client: starting a server\"",
")",
"\n",
"var",
"servers",
"[",
"]",
"*",
"types",
".",
"MockServer",
"\n",
"for",
"port",
",",
"s",
":=",
"range",
"p",
".",
"pactMockSvcManager",
".",
"List",
"(",
")",
"{",
"servers",
"=",
"append",
"(",
"servers",
",",
"&",
"types",
".",
"MockServer",
"{",
"Pid",
":",
"s",
".",
"Process",
".",
"Pid",
",",
"Port",
":",
"port",
",",
"}",
")",
"\n",
"}",
"\n",
"return",
"servers",
"\n",
"}"
] |
// ListServers lists all known Mock Servers
|
[
"ListServers",
"lists",
"all",
"known",
"Mock",
"Servers"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L108-L121
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
UpdateMessagePact
|
func (p *PactClient) UpdateMessagePact(request types.PactMessageRequest) error {
log.Println("[DEBUG] client: adding pact message...")
// Convert request into flags, and validate request
err := request.Validate()
if err != nil {
return err
}
svc := p.messageSvcManager.NewService(request.Args)
cmd := svc.Command()
stdOutPipe, err := cmd.StdoutPipe()
if err != nil {
return err
}
stdErrPipe, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
stdOut, err := ioutil.ReadAll(stdOutPipe)
if err != nil {
return err
}
stdErr, err := ioutil.ReadAll(stdErrPipe)
if err != nil {
return err
}
err = cmd.Wait()
if err == nil {
return nil
}
return fmt.Errorf("error creating message: %s\n\nSTDERR:\n%s\n\nSTDOUT:\n%s", err, stdErr, stdOut)
}
|
go
|
func (p *PactClient) UpdateMessagePact(request types.PactMessageRequest) error {
log.Println("[DEBUG] client: adding pact message...")
// Convert request into flags, and validate request
err := request.Validate()
if err != nil {
return err
}
svc := p.messageSvcManager.NewService(request.Args)
cmd := svc.Command()
stdOutPipe, err := cmd.StdoutPipe()
if err != nil {
return err
}
stdErrPipe, err := cmd.StderrPipe()
if err != nil {
return err
}
err = cmd.Start()
if err != nil {
return err
}
stdOut, err := ioutil.ReadAll(stdOutPipe)
if err != nil {
return err
}
stdErr, err := ioutil.ReadAll(stdErrPipe)
if err != nil {
return err
}
err = cmd.Wait()
if err == nil {
return nil
}
return fmt.Errorf("error creating message: %s\n\nSTDERR:\n%s\n\nSTDOUT:\n%s", err, stdErr, stdOut)
}
|
[
"func",
"(",
"p",
"*",
"PactClient",
")",
"UpdateMessagePact",
"(",
"request",
"types",
".",
"PactMessageRequest",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] client: adding pact message...\"",
")",
"\n",
"err",
":=",
"request",
".",
"Validate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"svc",
":=",
"p",
".",
"messageSvcManager",
".",
"NewService",
"(",
"request",
".",
"Args",
")",
"\n",
"cmd",
":=",
"svc",
".",
"Command",
"(",
")",
"\n",
"stdOutPipe",
",",
"err",
":=",
"cmd",
".",
"StdoutPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"stdErrPipe",
",",
"err",
":=",
"cmd",
".",
"StderrPipe",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"cmd",
".",
"Start",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"stdOut",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"stdOutPipe",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"stdErr",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"stdErrPipe",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Errorf",
"(",
"\"error creating message: %s\\n\\nSTDERR:\\n%s\\n\\nSTDOUT:\\n%s\"",
",",
"\\n",
",",
"\\n",
",",
"\\n",
")",
"\n",
"}"
] |
// UpdateMessagePact adds a pact message to a contract file
|
[
"UpdateMessagePact",
"adds",
"a",
"pact",
"message",
"to",
"a",
"contract",
"file"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L228-L268
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
PublishPacts
|
func (p *PactClient) PublishPacts(request types.PublishRequest) error {
svc := p.publishSvcManager.NewService(request.Args)
log.Println("[DEBUG] about to publish pacts")
cmd := svc.Start()
log.Println("[DEBUG] waiting for response")
err := cmd.Wait()
log.Println("[DEBUG] response from publish", err)
return err
}
|
go
|
func (p *PactClient) PublishPacts(request types.PublishRequest) error {
svc := p.publishSvcManager.NewService(request.Args)
log.Println("[DEBUG] about to publish pacts")
cmd := svc.Start()
log.Println("[DEBUG] waiting for response")
err := cmd.Wait()
log.Println("[DEBUG] response from publish", err)
return err
}
|
[
"func",
"(",
"p",
"*",
"PactClient",
")",
"PublishPacts",
"(",
"request",
"types",
".",
"PublishRequest",
")",
"error",
"{",
"svc",
":=",
"p",
".",
"publishSvcManager",
".",
"NewService",
"(",
"request",
".",
"Args",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] about to publish pacts\"",
")",
"\n",
"cmd",
":=",
"svc",
".",
"Start",
"(",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] waiting for response\"",
")",
"\n",
"err",
":=",
"cmd",
".",
"Wait",
"(",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] response from publish\"",
",",
"err",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// PublishPacts publishes a set of pacts to a pact broker
|
[
"PublishPacts",
"publishes",
"a",
"set",
"of",
"pacts",
"to",
"a",
"pact",
"broker"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L271-L282
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
getPort
|
func getPort(rawURL string) int {
parsedURL, err := url.Parse(rawURL)
if err == nil {
splitHost := strings.Split(parsedURL.Host, ":")
if len(splitHost) == 2 {
port, err := strconv.Atoi(splitHost[1])
if err == nil {
return port
}
}
if parsedURL.Scheme == "https" {
return 443
}
return 80
}
return -1
}
|
go
|
func getPort(rawURL string) int {
parsedURL, err := url.Parse(rawURL)
if err == nil {
splitHost := strings.Split(parsedURL.Host, ":")
if len(splitHost) == 2 {
port, err := strconv.Atoi(splitHost[1])
if err == nil {
return port
}
}
if parsedURL.Scheme == "https" {
return 443
}
return 80
}
return -1
}
|
[
"func",
"getPort",
"(",
"rawURL",
"string",
")",
"int",
"{",
"parsedURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"rawURL",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"splitHost",
":=",
"strings",
".",
"Split",
"(",
"parsedURL",
".",
"Host",
",",
"\":\"",
")",
"\n",
"if",
"len",
"(",
"splitHost",
")",
"==",
"2",
"{",
"port",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"splitHost",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"port",
"\n",
"}",
"\n",
"}",
"\n",
"if",
"parsedURL",
".",
"Scheme",
"==",
"\"https\"",
"{",
"return",
"443",
"\n",
"}",
"\n",
"return",
"80",
"\n",
"}",
"\n",
"return",
"-",
"1",
"\n",
"}"
] |
// Get a port given a URL
|
[
"Get",
"a",
"port",
"given",
"a",
"URL"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L349-L366
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
getAddress
|
func getAddress(rawURL string) string {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return ""
}
splitHost := strings.Split(parsedURL.Host, ":")
return splitHost[0]
}
|
go
|
func getAddress(rawURL string) string {
parsedURL, err := url.Parse(rawURL)
if err != nil {
return ""
}
splitHost := strings.Split(parsedURL.Host, ":")
return splitHost[0]
}
|
[
"func",
"getAddress",
"(",
"rawURL",
"string",
")",
"string",
"{",
"parsedURL",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"rawURL",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
"\n",
"}",
"\n",
"splitHost",
":=",
"strings",
".",
"Split",
"(",
"parsedURL",
".",
"Host",
",",
"\":\"",
")",
"\n",
"return",
"splitHost",
"[",
"0",
"]",
"\n",
"}"
] |
// Get the address given a URL
|
[
"Get",
"the",
"address",
"given",
"a",
"URL"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L369-L377
|
test
|
pact-foundation/pact-go
|
dsl/client.go
|
sanitiseRubyResponse
|
func sanitiseRubyResponse(response string) string {
log.Println("[TRACE] response from Ruby process pre-sanitisation:", response)
r := regexp.MustCompile("(?m)^\\s*#.*$")
s := r.ReplaceAllString(response, "")
r = regexp.MustCompile("(?m).*bundle exec rake pact:verify.*$")
s = r.ReplaceAllString(s, "")
r = regexp.MustCompile("\\n+")
s = r.ReplaceAllString(s, "\n")
return s
}
|
go
|
func sanitiseRubyResponse(response string) string {
log.Println("[TRACE] response from Ruby process pre-sanitisation:", response)
r := regexp.MustCompile("(?m)^\\s*#.*$")
s := r.ReplaceAllString(response, "")
r = regexp.MustCompile("(?m).*bundle exec rake pact:verify.*$")
s = r.ReplaceAllString(s, "")
r = regexp.MustCompile("\\n+")
s = r.ReplaceAllString(s, "\n")
return s
}
|
[
"func",
"sanitiseRubyResponse",
"(",
"response",
"string",
")",
"string",
"{",
"log",
".",
"Println",
"(",
"\"[TRACE] response from Ruby process pre-sanitisation:\"",
",",
"response",
")",
"\n",
"r",
":=",
"regexp",
".",
"MustCompile",
"(",
"\"(?m)^\\\\s*#.*$\"",
")",
"\n",
"\\\\",
"\n",
"s",
":=",
"r",
".",
"ReplaceAllString",
"(",
"response",
",",
"\"\"",
")",
"\n",
"r",
"=",
"regexp",
".",
"MustCompile",
"(",
"\"(?m).*bundle exec rake pact:verify.*$\"",
")",
"\n",
"s",
"=",
"r",
".",
"ReplaceAllString",
"(",
"s",
",",
"\"\"",
")",
"\n",
"r",
"=",
"regexp",
".",
"MustCompile",
"(",
"\"\\\\n+\"",
")",
"\n",
"\\\\",
"\n",
"}"
] |
// sanitiseRubyResponse removes Ruby-isms from the response content
// making the output much more human readable
|
[
"sanitiseRubyResponse",
"removes",
"Ruby",
"-",
"isms",
"from",
"the",
"response",
"content",
"making",
"the",
"output",
"much",
"more",
"human",
"readable"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/client.go#L401-L414
|
test
|
pact-foundation/pact-go
|
dsl/publish.go
|
Publish
|
func (p *Publisher) Publish(request types.PublishRequest) error {
log.Println("[DEBUG] pact publisher: publish pact")
if p.pactClient == nil {
c := NewClient()
p.pactClient = c
}
err := request.Validate()
if err != nil {
return err
}
return p.pactClient.PublishPacts(request)
}
|
go
|
func (p *Publisher) Publish(request types.PublishRequest) error {
log.Println("[DEBUG] pact publisher: publish pact")
if p.pactClient == nil {
c := NewClient()
p.pactClient = c
}
err := request.Validate()
if err != nil {
return err
}
return p.pactClient.PublishPacts(request)
}
|
[
"func",
"(",
"p",
"*",
"Publisher",
")",
"Publish",
"(",
"request",
"types",
".",
"PublishRequest",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] pact publisher: publish pact\"",
")",
"\n",
"if",
"p",
".",
"pactClient",
"==",
"nil",
"{",
"c",
":=",
"NewClient",
"(",
")",
"\n",
"p",
".",
"pactClient",
"=",
"c",
"\n",
"}",
"\n",
"err",
":=",
"request",
".",
"Validate",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"p",
".",
"pactClient",
".",
"PublishPacts",
"(",
"request",
")",
"\n",
"}"
] |
// Publish sends the Pacts to a broker, optionally tagging them
|
[
"Publish",
"sends",
"the",
"Pacts",
"to",
"a",
"broker",
"optionally",
"tagging",
"them"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/publish.go#L30-L45
|
test
|
pact-foundation/pact-go
|
utils/port.go
|
FindPortInRange
|
func FindPortInRange(s string) (int, error) {
// Take care of csv and single value
if !strings.Contains(s, "-") {
ports := strings.Split(strings.TrimSpace(s), ",")
for _, p := range ports {
i, err := strconv.Atoi(p)
if err != nil {
return 0, err
}
err = checkPort(i)
if err != nil {
continue
}
return i, nil
}
return 0, errors.New("all passed ports are unusable")
}
// Now take care of ranges
ports := strings.Split(strings.TrimSpace(s), "-")
if len(ports) != 2 {
return 0, errors.New("invalid range passed")
}
lower, err := strconv.Atoi(ports[0])
if err != nil {
return 0, err
}
upper, err := strconv.Atoi(ports[1])
if err != nil {
return 0, err
}
if upper < lower {
return 0, errors.New("invalid range passed")
}
for i := lower; i <= upper; i++ {
err = checkPort(i)
if err != nil {
continue
}
return i, nil
}
return 0, errors.New("all passed ports are unusable")
}
|
go
|
func FindPortInRange(s string) (int, error) {
// Take care of csv and single value
if !strings.Contains(s, "-") {
ports := strings.Split(strings.TrimSpace(s), ",")
for _, p := range ports {
i, err := strconv.Atoi(p)
if err != nil {
return 0, err
}
err = checkPort(i)
if err != nil {
continue
}
return i, nil
}
return 0, errors.New("all passed ports are unusable")
}
// Now take care of ranges
ports := strings.Split(strings.TrimSpace(s), "-")
if len(ports) != 2 {
return 0, errors.New("invalid range passed")
}
lower, err := strconv.Atoi(ports[0])
if err != nil {
return 0, err
}
upper, err := strconv.Atoi(ports[1])
if err != nil {
return 0, err
}
if upper < lower {
return 0, errors.New("invalid range passed")
}
for i := lower; i <= upper; i++ {
err = checkPort(i)
if err != nil {
continue
}
return i, nil
}
return 0, errors.New("all passed ports are unusable")
}
|
[
"func",
"FindPortInRange",
"(",
"s",
"string",
")",
"(",
"int",
",",
"error",
")",
"{",
"if",
"!",
"strings",
".",
"Contains",
"(",
"s",
",",
"\"-\"",
")",
"{",
"ports",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
",",
"\",\"",
")",
"\n",
"for",
"_",
",",
"p",
":=",
"range",
"ports",
"{",
"i",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"p",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"err",
"=",
"checkPort",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"all passed ports are unusable\"",
")",
"\n",
"}",
"\n",
"ports",
":=",
"strings",
".",
"Split",
"(",
"strings",
".",
"TrimSpace",
"(",
"s",
")",
",",
"\"-\"",
")",
"\n",
"if",
"len",
"(",
"ports",
")",
"!=",
"2",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"invalid range passed\"",
")",
"\n",
"}",
"\n",
"lower",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"ports",
"[",
"0",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"upper",
",",
"err",
":=",
"strconv",
".",
"Atoi",
"(",
"ports",
"[",
"1",
"]",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"0",
",",
"err",
"\n",
"}",
"\n",
"if",
"upper",
"<",
"lower",
"{",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"invalid range passed\"",
")",
"\n",
"}",
"\n",
"for",
"i",
":=",
"lower",
";",
"i",
"<=",
"upper",
";",
"i",
"++",
"{",
"err",
"=",
"checkPort",
"(",
"i",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"continue",
"\n",
"}",
"\n",
"return",
"i",
",",
"nil",
"\n",
"}",
"\n",
"return",
"0",
",",
"errors",
".",
"New",
"(",
"\"all passed ports are unusable\"",
")",
"\n",
"}"
] |
// FindPortInRange Iterate through CSV or Range of ports to find open port
// Valid inputs are "8081", "8081,8085", "8081-8085". Do not combine
// list and range
|
[
"FindPortInRange",
"Iterate",
"through",
"CSV",
"or",
"Range",
"of",
"ports",
"to",
"find",
"open",
"port",
"Valid",
"inputs",
"are",
"8081",
"8081",
"8085",
"8081",
"-",
"8085",
".",
"Do",
"not",
"combine",
"list",
"and",
"range"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/utils/port.go#L31-L72
|
test
|
pact-foundation/pact-go
|
dsl/matcher.go
|
EachLike
|
func EachLike(content interface{}, minRequired int) Matcher {
return eachLike{
Contents: content,
Min: minRequired,
}
}
|
go
|
func EachLike(content interface{}, minRequired int) Matcher {
return eachLike{
Contents: content,
Min: minRequired,
}
}
|
[
"func",
"EachLike",
"(",
"content",
"interface",
"{",
"}",
",",
"minRequired",
"int",
")",
"Matcher",
"{",
"return",
"eachLike",
"{",
"Contents",
":",
"content",
",",
"Min",
":",
"minRequired",
",",
"}",
"\n",
"}"
] |
// EachLike specifies that a given element in a JSON body can be repeated
// "minRequired" times. Number needs to be 1 or greater
|
[
"EachLike",
"specifies",
"that",
"a",
"given",
"element",
"in",
"a",
"JSON",
"body",
"can",
"be",
"repeated",
"minRequired",
"times",
".",
"Number",
"needs",
"to",
"be",
"1",
"or",
"greater"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L100-L105
|
test
|
pact-foundation/pact-go
|
dsl/matcher.go
|
Term
|
func Term(generate string, matcher string) Matcher {
return term{
Data: termData{
Generate: generate,
Matcher: termMatcher{
Type: "Regexp",
O: 0,
Regex: matcher,
},
},
}
}
|
go
|
func Term(generate string, matcher string) Matcher {
return term{
Data: termData{
Generate: generate,
Matcher: termMatcher{
Type: "Regexp",
O: 0,
Regex: matcher,
},
},
}
}
|
[
"func",
"Term",
"(",
"generate",
"string",
",",
"matcher",
"string",
")",
"Matcher",
"{",
"return",
"term",
"{",
"Data",
":",
"termData",
"{",
"Generate",
":",
"generate",
",",
"Matcher",
":",
"termMatcher",
"{",
"Type",
":",
"\"Regexp\"",
",",
"O",
":",
"0",
",",
"Regex",
":",
"matcher",
",",
"}",
",",
"}",
",",
"}",
"\n",
"}"
] |
// Term specifies that the matching should generate a value
// and also match using a regular expression.
|
[
"Term",
"specifies",
"that",
"the",
"matching",
"should",
"generate",
"a",
"value",
"and",
"also",
"match",
"using",
"a",
"regular",
"expression",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L117-L128
|
test
|
pact-foundation/pact-go
|
dsl/matcher.go
|
UnmarshalJSON
|
func (m *MapMatcher) UnmarshalJSON(bytes []byte) (err error) {
sk := make(map[string]string)
err = json.Unmarshal(bytes, &sk)
if err != nil {
return
}
*m = make(map[string]Matcher)
for k, v := range sk {
(*m)[k] = String(v)
}
return
}
|
go
|
func (m *MapMatcher) UnmarshalJSON(bytes []byte) (err error) {
sk := make(map[string]string)
err = json.Unmarshal(bytes, &sk)
if err != nil {
return
}
*m = make(map[string]Matcher)
for k, v := range sk {
(*m)[k] = String(v)
}
return
}
|
[
"func",
"(",
"m",
"*",
"MapMatcher",
")",
"UnmarshalJSON",
"(",
"bytes",
"[",
"]",
"byte",
")",
"(",
"err",
"error",
")",
"{",
"sk",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"string",
")",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"bytes",
",",
"&",
"sk",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"*",
"m",
"=",
"make",
"(",
"map",
"[",
"string",
"]",
"Matcher",
")",
"\n",
"for",
"k",
",",
"v",
":=",
"range",
"sk",
"{",
"(",
"*",
"m",
")",
"[",
"k",
"]",
"=",
"String",
"(",
"v",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// UnmarshalJSON is a custom JSON parser for MapMatcher
// It treats the matchers as strings
|
[
"UnmarshalJSON",
"is",
"a",
"custom",
"JSON",
"parser",
"for",
"MapMatcher",
"It",
"treats",
"the",
"matchers",
"as",
"strings"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L245-L258
|
test
|
pact-foundation/pact-go
|
dsl/matcher.go
|
objectToString
|
func objectToString(obj interface{}) string {
switch content := obj.(type) {
case string:
return content
default:
jsonString, err := json.Marshal(obj)
if err != nil {
log.Println("[DEBUG] objectToString: error unmarshaling object into string:", err.Error())
return ""
}
return string(jsonString)
}
}
|
go
|
func objectToString(obj interface{}) string {
switch content := obj.(type) {
case string:
return content
default:
jsonString, err := json.Marshal(obj)
if err != nil {
log.Println("[DEBUG] objectToString: error unmarshaling object into string:", err.Error())
return ""
}
return string(jsonString)
}
}
|
[
"func",
"objectToString",
"(",
"obj",
"interface",
"{",
"}",
")",
"string",
"{",
"switch",
"content",
":=",
"obj",
".",
"(",
"type",
")",
"{",
"case",
"string",
":",
"return",
"content",
"\n",
"default",
":",
"jsonString",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"obj",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] objectToString: error unmarshaling object into string:\"",
",",
"err",
".",
"Error",
"(",
")",
")",
"\n",
"return",
"\"\"",
"\n",
"}",
"\n",
"return",
"string",
"(",
"jsonString",
")",
"\n",
"}",
"\n",
"}"
] |
// Takes an object and converts it to a JSON representation
|
[
"Takes",
"an",
"object",
"and",
"converts",
"it",
"to",
"a",
"JSON",
"representation"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L261-L273
|
test
|
pact-foundation/pact-go
|
dsl/matcher.go
|
match
|
func match(srcType reflect.Type, params params) Matcher {
switch kind := srcType.Kind(); kind {
case reflect.Ptr:
return match(srcType.Elem(), params)
case reflect.Slice, reflect.Array:
return EachLike(match(srcType.Elem(), getDefaults()), params.slice.min)
case reflect.Struct:
result := StructMatcher{}
for i := 0; i < srcType.NumField(); i++ {
field := srcType.Field(i)
result[field.Tag.Get("json")] = match(field.Type, pluckParams(field.Type, field.Tag.Get("pact")))
}
return result
case reflect.String:
if params.str.regEx != "" {
return Term(params.str.example, params.str.regEx)
}
if params.str.example != "" {
return Like(params.str.example)
}
return Like("string")
case reflect.Bool:
return Like(true)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Like(1)
case reflect.Float32, reflect.Float64:
return Like(1.1)
default:
panic(fmt.Sprintf("match: unhandled type: %v", srcType))
}
}
|
go
|
func match(srcType reflect.Type, params params) Matcher {
switch kind := srcType.Kind(); kind {
case reflect.Ptr:
return match(srcType.Elem(), params)
case reflect.Slice, reflect.Array:
return EachLike(match(srcType.Elem(), getDefaults()), params.slice.min)
case reflect.Struct:
result := StructMatcher{}
for i := 0; i < srcType.NumField(); i++ {
field := srcType.Field(i)
result[field.Tag.Get("json")] = match(field.Type, pluckParams(field.Type, field.Tag.Get("pact")))
}
return result
case reflect.String:
if params.str.regEx != "" {
return Term(params.str.example, params.str.regEx)
}
if params.str.example != "" {
return Like(params.str.example)
}
return Like("string")
case reflect.Bool:
return Like(true)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Like(1)
case reflect.Float32, reflect.Float64:
return Like(1.1)
default:
panic(fmt.Sprintf("match: unhandled type: %v", srcType))
}
}
|
[
"func",
"match",
"(",
"srcType",
"reflect",
".",
"Type",
",",
"params",
"params",
")",
"Matcher",
"{",
"switch",
"kind",
":=",
"srcType",
".",
"Kind",
"(",
")",
";",
"kind",
"{",
"case",
"reflect",
".",
"Ptr",
":",
"return",
"match",
"(",
"srcType",
".",
"Elem",
"(",
")",
",",
"params",
")",
"\n",
"case",
"reflect",
".",
"Slice",
",",
"reflect",
".",
"Array",
":",
"return",
"EachLike",
"(",
"match",
"(",
"srcType",
".",
"Elem",
"(",
")",
",",
"getDefaults",
"(",
")",
")",
",",
"params",
".",
"slice",
".",
"min",
")",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"result",
":=",
"StructMatcher",
"{",
"}",
"\n",
"for",
"i",
":=",
"0",
";",
"i",
"<",
"srcType",
".",
"NumField",
"(",
")",
";",
"i",
"++",
"{",
"field",
":=",
"srcType",
".",
"Field",
"(",
"i",
")",
"\n",
"result",
"[",
"field",
".",
"Tag",
".",
"Get",
"(",
"\"json\"",
")",
"]",
"=",
"match",
"(",
"field",
".",
"Type",
",",
"pluckParams",
"(",
"field",
".",
"Type",
",",
"field",
".",
"Tag",
".",
"Get",
"(",
"\"pact\"",
")",
")",
")",
"\n",
"}",
"\n",
"return",
"result",
"\n",
"case",
"reflect",
".",
"String",
":",
"if",
"params",
".",
"str",
".",
"regEx",
"!=",
"\"\"",
"{",
"return",
"Term",
"(",
"params",
".",
"str",
".",
"example",
",",
"params",
".",
"str",
".",
"regEx",
")",
"\n",
"}",
"\n",
"if",
"params",
".",
"str",
".",
"example",
"!=",
"\"\"",
"{",
"return",
"Like",
"(",
"params",
".",
"str",
".",
"example",
")",
"\n",
"}",
"\n",
"return",
"Like",
"(",
"\"string\"",
")",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"return",
"Like",
"(",
"true",
")",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
",",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"return",
"Like",
"(",
"1",
")",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"return",
"Like",
"(",
"1.1",
")",
"\n",
"default",
":",
"panic",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"match: unhandled type: %v\"",
",",
"srcType",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// match recursively traverses the provided type and outputs a
// matcher string for it that is compatible with the Pact dsl.
|
[
"match",
"recursively",
"traverses",
"the",
"provided",
"type",
"and",
"outputs",
"a",
"matcher",
"string",
"for",
"it",
"that",
"is",
"compatible",
"with",
"the",
"Pact",
"dsl",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/matcher.go#L291-L324
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
AddMessage
|
func (p *Pact) AddMessage() *Message {
log.Println("[DEBUG] pact add message")
m := &Message{}
p.MessageInteractions = append(p.MessageInteractions, m)
return m
}
|
go
|
func (p *Pact) AddMessage() *Message {
log.Println("[DEBUG] pact add message")
m := &Message{}
p.MessageInteractions = append(p.MessageInteractions, m)
return m
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"AddMessage",
"(",
")",
"*",
"Message",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] pact add message\"",
")",
"\n",
"m",
":=",
"&",
"Message",
"{",
"}",
"\n",
"p",
".",
"MessageInteractions",
"=",
"append",
"(",
"p",
".",
"MessageInteractions",
",",
"m",
")",
"\n",
"return",
"m",
"\n",
"}"
] |
// AddMessage creates a new asynchronous consumer expectation
|
[
"AddMessage",
"creates",
"a",
"new",
"asynchronous",
"consumer",
"expectation"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L104-L110
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
AddInteraction
|
func (p *Pact) AddInteraction() *Interaction {
p.Setup(true)
log.Println("[DEBUG] pact add interaction")
i := &Interaction{}
p.Interactions = append(p.Interactions, i)
return i
}
|
go
|
func (p *Pact) AddInteraction() *Interaction {
p.Setup(true)
log.Println("[DEBUG] pact add interaction")
i := &Interaction{}
p.Interactions = append(p.Interactions, i)
return i
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"AddInteraction",
"(",
")",
"*",
"Interaction",
"{",
"p",
".",
"Setup",
"(",
"true",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] pact add interaction\"",
")",
"\n",
"i",
":=",
"&",
"Interaction",
"{",
"}",
"\n",
"p",
".",
"Interactions",
"=",
"append",
"(",
"p",
".",
"Interactions",
",",
"i",
")",
"\n",
"return",
"i",
"\n",
"}"
] |
// AddInteraction creates a new Pact interaction, initialising all
// required things. Will automatically start a Mock Service if none running.
|
[
"AddInteraction",
"creates",
"a",
"new",
"Pact",
"interaction",
"initialising",
"all",
"required",
"things",
".",
"Will",
"automatically",
"start",
"a",
"Mock",
"Service",
"if",
"none",
"running",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L114-L120
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
Teardown
|
func (p *Pact) Teardown() *Pact {
log.Println("[DEBUG] teardown")
if p.Server != nil {
server, err := p.pactClient.StopServer(p.Server)
if err != nil {
log.Println("error:", err)
}
p.Server = server
}
return p
}
|
go
|
func (p *Pact) Teardown() *Pact {
log.Println("[DEBUG] teardown")
if p.Server != nil {
server, err := p.pactClient.StopServer(p.Server)
if err != nil {
log.Println("error:", err)
}
p.Server = server
}
return p
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"Teardown",
"(",
")",
"*",
"Pact",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] teardown\"",
")",
"\n",
"if",
"p",
".",
"Server",
"!=",
"nil",
"{",
"server",
",",
"err",
":=",
"p",
".",
"pactClient",
".",
"StopServer",
"(",
"p",
".",
"Server",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Println",
"(",
"\"error:\"",
",",
"err",
")",
"\n",
"}",
"\n",
"p",
".",
"Server",
"=",
"server",
"\n",
"}",
"\n",
"return",
"p",
"\n",
"}"
] |
// Teardown stops the Pact Mock Server. This usually is called on completion
// of each test suite.
|
[
"Teardown",
"stops",
"the",
"Pact",
"Mock",
"Server",
".",
"This",
"usually",
"is",
"called",
"on",
"completion",
"of",
"each",
"test",
"suite",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L222-L233
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
Verify
|
func (p *Pact) Verify(integrationTest func() error) error {
p.Setup(true)
log.Println("[DEBUG] pact verify")
// Check if we are verifying messages or if we actually have interactions
if len(p.Interactions) == 0 {
return errors.New("there are no interactions to be verified")
}
mockServer := &MockService{
BaseURL: fmt.Sprintf("http://%s:%d", p.Host, p.Server.Port),
Consumer: p.Consumer,
Provider: p.Provider,
}
for _, interaction := range p.Interactions {
err := mockServer.AddInteraction(interaction)
if err != nil {
return err
}
}
// Run the integration test
err := integrationTest()
if err != nil {
return err
}
// Run Verification Process
err = mockServer.Verify()
if err != nil {
return err
}
// Clear out interations
p.Interactions = make([]*Interaction, 0)
return mockServer.DeleteInteractions()
}
|
go
|
func (p *Pact) Verify(integrationTest func() error) error {
p.Setup(true)
log.Println("[DEBUG] pact verify")
// Check if we are verifying messages or if we actually have interactions
if len(p.Interactions) == 0 {
return errors.New("there are no interactions to be verified")
}
mockServer := &MockService{
BaseURL: fmt.Sprintf("http://%s:%d", p.Host, p.Server.Port),
Consumer: p.Consumer,
Provider: p.Provider,
}
for _, interaction := range p.Interactions {
err := mockServer.AddInteraction(interaction)
if err != nil {
return err
}
}
// Run the integration test
err := integrationTest()
if err != nil {
return err
}
// Run Verification Process
err = mockServer.Verify()
if err != nil {
return err
}
// Clear out interations
p.Interactions = make([]*Interaction, 0)
return mockServer.DeleteInteractions()
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"Verify",
"(",
"integrationTest",
"func",
"(",
")",
"error",
")",
"error",
"{",
"p",
".",
"Setup",
"(",
"true",
")",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] pact verify\"",
")",
"\n",
"if",
"len",
"(",
"p",
".",
"Interactions",
")",
"==",
"0",
"{",
"return",
"errors",
".",
"New",
"(",
"\"there are no interactions to be verified\"",
")",
"\n",
"}",
"\n",
"mockServer",
":=",
"&",
"MockService",
"{",
"BaseURL",
":",
"fmt",
".",
"Sprintf",
"(",
"\"http://%s:%d\"",
",",
"p",
".",
"Host",
",",
"p",
".",
"Server",
".",
"Port",
")",
",",
"Consumer",
":",
"p",
".",
"Consumer",
",",
"Provider",
":",
"p",
".",
"Provider",
",",
"}",
"\n",
"for",
"_",
",",
"interaction",
":=",
"range",
"p",
".",
"Interactions",
"{",
"err",
":=",
"mockServer",
".",
"AddInteraction",
"(",
"interaction",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"}",
"\n",
"err",
":=",
"integrationTest",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"err",
"=",
"mockServer",
".",
"Verify",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"p",
".",
"Interactions",
"=",
"make",
"(",
"[",
"]",
"*",
"Interaction",
",",
"0",
")",
"\n",
"return",
"mockServer",
".",
"DeleteInteractions",
"(",
")",
"\n",
"}"
] |
// Verify runs the current test case against a Mock Service.
// Will cleanup interactions between tests within a suite.
|
[
"Verify",
"runs",
"the",
"current",
"test",
"case",
"against",
"a",
"Mock",
"Service",
".",
"Will",
"cleanup",
"interactions",
"between",
"tests",
"within",
"a",
"suite",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L237-L275
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
stateHandlerMiddleware
|
func stateHandlerMiddleware(stateHandlers types.StateHandlers) proxy.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/__setup" {
var s *types.ProviderState
decoder := json.NewDecoder(r.Body)
decoder.Decode(&s)
// Setup any provider state
for _, state := range s.States {
sf, stateFound := stateHandlers[state]
if !stateFound {
log.Printf("[WARN] state handler not found for state: %v", state)
} else {
// Execute state handler
if err := sf(); err != nil {
log.Printf("[ERROR] state handler for '%v' errored: %v", state, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
w.WriteHeader(http.StatusOK)
return
}
log.Println("[DEBUG] skipping state handler for request", r.RequestURI)
// Pass through to application
next.ServeHTTP(w, r)
})
}
}
|
go
|
func stateHandlerMiddleware(stateHandlers types.StateHandlers) proxy.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/__setup" {
var s *types.ProviderState
decoder := json.NewDecoder(r.Body)
decoder.Decode(&s)
// Setup any provider state
for _, state := range s.States {
sf, stateFound := stateHandlers[state]
if !stateFound {
log.Printf("[WARN] state handler not found for state: %v", state)
} else {
// Execute state handler
if err := sf(); err != nil {
log.Printf("[ERROR] state handler for '%v' errored: %v", state, err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
}
w.WriteHeader(http.StatusOK)
return
}
log.Println("[DEBUG] skipping state handler for request", r.RequestURI)
// Pass through to application
next.ServeHTTP(w, r)
})
}
}
|
[
"func",
"stateHandlerMiddleware",
"(",
"stateHandlers",
"types",
".",
"StateHandlers",
")",
"proxy",
".",
"Middleware",
"{",
"return",
"func",
"(",
"next",
"http",
".",
"Handler",
")",
"http",
".",
"Handler",
"{",
"return",
"http",
".",
"HandlerFunc",
"(",
"func",
"(",
"w",
"http",
".",
"ResponseWriter",
",",
"r",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"r",
".",
"URL",
".",
"Path",
"==",
"\"/__setup\"",
"{",
"var",
"s",
"*",
"types",
".",
"ProviderState",
"\n",
"decoder",
":=",
"json",
".",
"NewDecoder",
"(",
"r",
".",
"Body",
")",
"\n",
"decoder",
".",
"Decode",
"(",
"&",
"s",
")",
"\n",
"for",
"_",
",",
"state",
":=",
"range",
"s",
".",
"States",
"{",
"sf",
",",
"stateFound",
":=",
"stateHandlers",
"[",
"state",
"]",
"\n",
"if",
"!",
"stateFound",
"{",
"log",
".",
"Printf",
"(",
"\"[WARN] state handler not found for state: %v\"",
",",
"state",
")",
"\n",
"}",
"else",
"{",
"if",
"err",
":=",
"sf",
"(",
")",
";",
"err",
"!=",
"nil",
"{",
"log",
".",
"Printf",
"(",
"\"[ERROR] state handler for '%v' errored: %v\"",
",",
"state",
",",
"err",
")",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusInternalServerError",
")",
"\n",
"return",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"w",
".",
"WriteHeader",
"(",
"http",
".",
"StatusOK",
")",
"\n",
"return",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] skipping state handler for request\"",
",",
"r",
".",
"RequestURI",
")",
"\n",
"next",
".",
"ServeHTTP",
"(",
"w",
",",
"r",
")",
"\n",
"}",
")",
"\n",
"}",
"\n",
"}"
] |
// stateHandlerMiddleware responds to the various states that are
// given during provider verification
//
// statehandler accepts a state object from the verifier and executes
// any state handlers associated with the provider.
// It will not execute further middleware if it is the designted "state" request
|
[
"stateHandlerMiddleware",
"responds",
"to",
"the",
"various",
"states",
"that",
"are",
"given",
"during",
"provider",
"verification",
"statehandler",
"accepts",
"a",
"state",
"object",
"from",
"the",
"verifier",
"and",
"executes",
"any",
"state",
"handlers",
"associated",
"with",
"the",
"provider",
".",
"It",
"will",
"not",
"execute",
"further",
"middleware",
"if",
"it",
"is",
"the",
"designted",
"state",
"request"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L456-L490
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
VerifyMessageProviderRaw
|
func (p *Pact) VerifyMessageProviderRaw(request VerifyMessageRequest) (types.ProviderVerifierResponse, error) {
p.Setup(false)
response := types.ProviderVerifierResponse{}
// Starts the message wrapper API with hooks back to the message handlers
// This maps the 'description' field of a message pact, to a function handler
// that will implement the message producer. This function must return an object and optionally
// and error. The object will be marshalled to JSON for comparison.
mux := http.NewServeMux()
port, err := utils.GetFreePort()
if err != nil {
return response, fmt.Errorf("unable to allocate a port for verification: %v", err)
}
// Construct verifier request
verificationRequest := types.VerifyRequest{
ProviderBaseURL: fmt.Sprintf("http://localhost:%d", port),
PactURLs: request.PactURLs,
BrokerURL: request.BrokerURL,
Tags: request.Tags,
BrokerUsername: request.BrokerUsername,
BrokerPassword: request.BrokerPassword,
BrokerToken: request.BrokerToken,
PublishVerificationResults: request.PublishVerificationResults,
ProviderVersion: request.ProviderVersion,
Provider: p.Provider,
}
mux.HandleFunc("/", messageVerificationHandler(request.MessageHandlers, request.StateHandlers))
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Printf("[DEBUG] API handler starting: port %d (%s)", port, ln.Addr())
go http.Serve(ln, mux)
portErr := waitForPort(port, "tcp", "localhost", p.ClientTimeout,
fmt.Sprintf(`Timed out waiting for pact proxy on port %d - check for errors`, port))
if portErr != nil {
log.Fatal("Error:", err)
return response, portErr
}
log.Println("[DEBUG] pact provider verification")
return p.pactClient.VerifyProvider(verificationRequest)
}
|
go
|
func (p *Pact) VerifyMessageProviderRaw(request VerifyMessageRequest) (types.ProviderVerifierResponse, error) {
p.Setup(false)
response := types.ProviderVerifierResponse{}
// Starts the message wrapper API with hooks back to the message handlers
// This maps the 'description' field of a message pact, to a function handler
// that will implement the message producer. This function must return an object and optionally
// and error. The object will be marshalled to JSON for comparison.
mux := http.NewServeMux()
port, err := utils.GetFreePort()
if err != nil {
return response, fmt.Errorf("unable to allocate a port for verification: %v", err)
}
// Construct verifier request
verificationRequest := types.VerifyRequest{
ProviderBaseURL: fmt.Sprintf("http://localhost:%d", port),
PactURLs: request.PactURLs,
BrokerURL: request.BrokerURL,
Tags: request.Tags,
BrokerUsername: request.BrokerUsername,
BrokerPassword: request.BrokerPassword,
BrokerToken: request.BrokerToken,
PublishVerificationResults: request.PublishVerificationResults,
ProviderVersion: request.ProviderVersion,
Provider: p.Provider,
}
mux.HandleFunc("/", messageVerificationHandler(request.MessageHandlers, request.StateHandlers))
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Printf("[DEBUG] API handler starting: port %d (%s)", port, ln.Addr())
go http.Serve(ln, mux)
portErr := waitForPort(port, "tcp", "localhost", p.ClientTimeout,
fmt.Sprintf(`Timed out waiting for pact proxy on port %d - check for errors`, port))
if portErr != nil {
log.Fatal("Error:", err)
return response, portErr
}
log.Println("[DEBUG] pact provider verification")
return p.pactClient.VerifyProvider(verificationRequest)
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"VerifyMessageProviderRaw",
"(",
"request",
"VerifyMessageRequest",
")",
"(",
"types",
".",
"ProviderVerifierResponse",
",",
"error",
")",
"{",
"p",
".",
"Setup",
"(",
"false",
")",
"\n",
"response",
":=",
"types",
".",
"ProviderVerifierResponse",
"{",
"}",
"\n",
"mux",
":=",
"http",
".",
"NewServeMux",
"(",
")",
"\n",
"port",
",",
"err",
":=",
"utils",
".",
"GetFreePort",
"(",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"response",
",",
"fmt",
".",
"Errorf",
"(",
"\"unable to allocate a port for verification: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"verificationRequest",
":=",
"types",
".",
"VerifyRequest",
"{",
"ProviderBaseURL",
":",
"fmt",
".",
"Sprintf",
"(",
"\"http://localhost:%d\"",
",",
"port",
")",
",",
"PactURLs",
":",
"request",
".",
"PactURLs",
",",
"BrokerURL",
":",
"request",
".",
"BrokerURL",
",",
"Tags",
":",
"request",
".",
"Tags",
",",
"BrokerUsername",
":",
"request",
".",
"BrokerUsername",
",",
"BrokerPassword",
":",
"request",
".",
"BrokerPassword",
",",
"BrokerToken",
":",
"request",
".",
"BrokerToken",
",",
"PublishVerificationResults",
":",
"request",
".",
"PublishVerificationResults",
",",
"ProviderVersion",
":",
"request",
".",
"ProviderVersion",
",",
"Provider",
":",
"p",
".",
"Provider",
",",
"}",
"\n",
"mux",
".",
"HandleFunc",
"(",
"\"/\"",
",",
"messageVerificationHandler",
"(",
"request",
".",
"MessageHandlers",
",",
"request",
".",
"StateHandlers",
")",
")",
"\n",
"ln",
",",
"err",
":=",
"net",
".",
"Listen",
"(",
"\"tcp\"",
",",
"fmt",
".",
"Sprintf",
"(",
"\":%d\"",
",",
"port",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"err",
")",
"\n",
"}",
"\n",
"defer",
"ln",
".",
"Close",
"(",
")",
"\n",
"log",
".",
"Printf",
"(",
"\"[DEBUG] API handler starting: port %d (%s)\"",
",",
"port",
",",
"ln",
".",
"Addr",
"(",
")",
")",
"\n",
"go",
"http",
".",
"Serve",
"(",
"ln",
",",
"mux",
")",
"\n",
"portErr",
":=",
"waitForPort",
"(",
"port",
",",
"\"tcp\"",
",",
"\"localhost\"",
",",
"p",
".",
"ClientTimeout",
",",
"fmt",
".",
"Sprintf",
"(",
"`Timed out waiting for pact proxy on port %d - check for errors`",
",",
"port",
")",
")",
"\n",
"if",
"portErr",
"!=",
"nil",
"{",
"log",
".",
"Fatal",
"(",
"\"Error:\"",
",",
"err",
")",
"\n",
"return",
"response",
",",
"portErr",
"\n",
"}",
"\n",
"log",
".",
"Println",
"(",
"\"[DEBUG] pact provider verification\"",
")",
"\n",
"return",
"p",
".",
"pactClient",
".",
"VerifyProvider",
"(",
"verificationRequest",
")",
"\n",
"}"
] |
// VerifyMessageProviderRaw runs provider message verification.
//
// A Message Producer is analagous to Consumer in the HTTP Interaction model.
// It is the initiator of an interaction, and expects something on the other end
// of the interaction to respond - just in this case, not immediately.
|
[
"VerifyMessageProviderRaw",
"runs",
"provider",
"message",
"verification",
".",
"A",
"Message",
"Producer",
"is",
"analagous",
"to",
"Consumer",
"in",
"the",
"HTTP",
"Interaction",
"model",
".",
"It",
"is",
"the",
"initiator",
"of",
"an",
"interaction",
"and",
"expects",
"something",
"on",
"the",
"other",
"end",
"of",
"the",
"interaction",
"to",
"respond",
"-",
"just",
"in",
"this",
"case",
"not",
"immediately",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L591-L641
|
test
|
pact-foundation/pact-go
|
dsl/pact.go
|
VerifyMessageConsumerRaw
|
func (p *Pact) VerifyMessageConsumerRaw(message *Message, handler MessageConsumer) error {
log.Printf("[DEBUG] verify message")
p.Setup(false)
// Reify the message back to its "example/generated" form
reified, err := p.pactClient.ReifyMessage(&types.PactReificationRequest{
Message: message.Content,
})
if err != nil {
return fmt.Errorf("unable to convert consumer test to a valid JSON representation: %v", err)
}
t := reflect.TypeOf(message.Type)
if t != nil && t.Name() != "interface" {
log.Println("[DEBUG] narrowing type to", t.Name())
err = json.Unmarshal(reified.ResponseRaw, &message.Type)
if err != nil {
return fmt.Errorf("unable to narrow type to %v: %v", t.Name(), err)
}
}
// Yield message, and send through handler function
generatedMessage :=
Message{
Content: message.Type,
States: message.States,
Description: message.Description,
Metadata: message.Metadata,
}
err = handler(generatedMessage)
if err != nil {
return err
}
// If no errors, update Message Pact
return p.pactClient.UpdateMessagePact(types.PactMessageRequest{
Message: message,
Consumer: p.Consumer,
Provider: p.Provider,
PactDir: p.PactDir,
})
}
|
go
|
func (p *Pact) VerifyMessageConsumerRaw(message *Message, handler MessageConsumer) error {
log.Printf("[DEBUG] verify message")
p.Setup(false)
// Reify the message back to its "example/generated" form
reified, err := p.pactClient.ReifyMessage(&types.PactReificationRequest{
Message: message.Content,
})
if err != nil {
return fmt.Errorf("unable to convert consumer test to a valid JSON representation: %v", err)
}
t := reflect.TypeOf(message.Type)
if t != nil && t.Name() != "interface" {
log.Println("[DEBUG] narrowing type to", t.Name())
err = json.Unmarshal(reified.ResponseRaw, &message.Type)
if err != nil {
return fmt.Errorf("unable to narrow type to %v: %v", t.Name(), err)
}
}
// Yield message, and send through handler function
generatedMessage :=
Message{
Content: message.Type,
States: message.States,
Description: message.Description,
Metadata: message.Metadata,
}
err = handler(generatedMessage)
if err != nil {
return err
}
// If no errors, update Message Pact
return p.pactClient.UpdateMessagePact(types.PactMessageRequest{
Message: message,
Consumer: p.Consumer,
Provider: p.Provider,
PactDir: p.PactDir,
})
}
|
[
"func",
"(",
"p",
"*",
"Pact",
")",
"VerifyMessageConsumerRaw",
"(",
"message",
"*",
"Message",
",",
"handler",
"MessageConsumer",
")",
"error",
"{",
"log",
".",
"Printf",
"(",
"\"[DEBUG] verify message\"",
")",
"\n",
"p",
".",
"Setup",
"(",
"false",
")",
"\n",
"reified",
",",
"err",
":=",
"p",
".",
"pactClient",
".",
"ReifyMessage",
"(",
"&",
"types",
".",
"PactReificationRequest",
"{",
"Message",
":",
"message",
".",
"Content",
",",
"}",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unable to convert consumer test to a valid JSON representation: %v\"",
",",
"err",
")",
"\n",
"}",
"\n",
"t",
":=",
"reflect",
".",
"TypeOf",
"(",
"message",
".",
"Type",
")",
"\n",
"if",
"t",
"!=",
"nil",
"&&",
"t",
".",
"Name",
"(",
")",
"!=",
"\"interface\"",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] narrowing type to\"",
",",
"t",
".",
"Name",
"(",
")",
")",
"\n",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"reified",
".",
"ResponseRaw",
",",
"&",
"message",
".",
"Type",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unable to narrow type to %v: %v\"",
",",
"t",
".",
"Name",
"(",
")",
",",
"err",
")",
"\n",
"}",
"\n",
"}",
"\n",
"generatedMessage",
":=",
"Message",
"{",
"Content",
":",
"message",
".",
"Type",
",",
"States",
":",
"message",
".",
"States",
",",
"Description",
":",
"message",
".",
"Description",
",",
"Metadata",
":",
"message",
".",
"Metadata",
",",
"}",
"\n",
"err",
"=",
"handler",
"(",
"generatedMessage",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"p",
".",
"pactClient",
".",
"UpdateMessagePact",
"(",
"types",
".",
"PactMessageRequest",
"{",
"Message",
":",
"message",
",",
"Consumer",
":",
"p",
".",
"Consumer",
",",
"Provider",
":",
"p",
".",
"Provider",
",",
"PactDir",
":",
"p",
".",
"PactDir",
",",
"}",
")",
"\n",
"}"
] |
// VerifyMessageConsumerRaw creates a new Pact _message_ interaction to build a testable
// interaction.
//
//
// A Message Consumer is analagous to a Provider in the HTTP Interaction model.
// It is the receiver of an interaction, and needs to be able to handle whatever
// request was provided.
|
[
"VerifyMessageConsumerRaw",
"creates",
"a",
"new",
"Pact",
"_message_",
"interaction",
"to",
"build",
"a",
"testable",
"interaction",
".",
"A",
"Message",
"Consumer",
"is",
"analagous",
"to",
"a",
"Provider",
"in",
"the",
"HTTP",
"Interaction",
"model",
".",
"It",
"is",
"the",
"receiver",
"of",
"an",
"interaction",
"and",
"needs",
"to",
"be",
"able",
"to",
"handle",
"whatever",
"request",
"was",
"provided",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/pact.go#L650-L694
|
test
|
pact-foundation/pact-go
|
dsl/mock_client.go
|
VerifyProvider
|
func (p *mockClient) VerifyProvider(request types.VerifyRequest) (types.ProviderVerifierResponse, error) {
return p.VerifyProviderResponse, p.VerifyProviderError
}
|
go
|
func (p *mockClient) VerifyProvider(request types.VerifyRequest) (types.ProviderVerifierResponse, error) {
return p.VerifyProviderResponse, p.VerifyProviderError
}
|
[
"func",
"(",
"p",
"*",
"mockClient",
")",
"VerifyProvider",
"(",
"request",
"types",
".",
"VerifyRequest",
")",
"(",
"types",
".",
"ProviderVerifierResponse",
",",
"error",
")",
"{",
"return",
"p",
".",
"VerifyProviderResponse",
",",
"p",
".",
"VerifyProviderError",
"\n",
"}"
] |
// VerifyProvider runs the verification process against a running Provider.
|
[
"VerifyProvider",
"runs",
"the",
"verification",
"process",
"against",
"a",
"running",
"Provider",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_client.go#L60-L62
|
test
|
pact-foundation/pact-go
|
client/mock_service.go
|
NewService
|
func (m *MockService) NewService(args []string) Service {
m.Args = []string{
"service",
}
m.Args = append(m.Args, args...)
m.Cmd = getMockServiceCommandPath()
return m
}
|
go
|
func (m *MockService) NewService(args []string) Service {
m.Args = []string{
"service",
}
m.Args = append(m.Args, args...)
m.Cmd = getMockServiceCommandPath()
return m
}
|
[
"func",
"(",
"m",
"*",
"MockService",
")",
"NewService",
"(",
"args",
"[",
"]",
"string",
")",
"Service",
"{",
"m",
".",
"Args",
"=",
"[",
"]",
"string",
"{",
"\"service\"",
",",
"}",
"\n",
"m",
".",
"Args",
"=",
"append",
"(",
"m",
".",
"Args",
",",
"args",
"...",
")",
"\n",
"m",
".",
"Cmd",
"=",
"getMockServiceCommandPath",
"(",
")",
"\n",
"return",
"m",
"\n",
"}"
] |
// NewService creates a new MockService with default settings.
|
[
"NewService",
"creates",
"a",
"new",
"MockService",
"with",
"default",
"settings",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/mock_service.go#L9-L17
|
test
|
pact-foundation/pact-go
|
client/service_manager.go
|
Setup
|
func (s *ServiceManager) Setup() {
log.Println("[DEBUG] setting up a service manager")
s.commandCreatedChan = make(chan *exec.Cmd)
s.commandCompleteChan = make(chan *exec.Cmd)
s.processMap = processMap{processes: make(map[int]*exec.Cmd)}
// Listen for service create/kill
go s.addServiceMonitor()
go s.removeServiceMonitor()
}
|
go
|
func (s *ServiceManager) Setup() {
log.Println("[DEBUG] setting up a service manager")
s.commandCreatedChan = make(chan *exec.Cmd)
s.commandCompleteChan = make(chan *exec.Cmd)
s.processMap = processMap{processes: make(map[int]*exec.Cmd)}
// Listen for service create/kill
go s.addServiceMonitor()
go s.removeServiceMonitor()
}
|
[
"func",
"(",
"s",
"*",
"ServiceManager",
")",
"Setup",
"(",
")",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] setting up a service manager\"",
")",
"\n",
"s",
".",
"commandCreatedChan",
"=",
"make",
"(",
"chan",
"*",
"exec",
".",
"Cmd",
")",
"\n",
"s",
".",
"commandCompleteChan",
"=",
"make",
"(",
"chan",
"*",
"exec",
".",
"Cmd",
")",
"\n",
"s",
".",
"processMap",
"=",
"processMap",
"{",
"processes",
":",
"make",
"(",
"map",
"[",
"int",
"]",
"*",
"exec",
".",
"Cmd",
")",
"}",
"\n",
"go",
"s",
".",
"addServiceMonitor",
"(",
")",
"\n",
"go",
"s",
".",
"removeServiceMonitor",
"(",
")",
"\n",
"}"
] |
// Setup the Management services.
|
[
"Setup",
"the",
"Management",
"services",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L23-L33
|
test
|
pact-foundation/pact-go
|
client/service_manager.go
|
addServiceMonitor
|
func (s *ServiceManager) addServiceMonitor() {
log.Println("[DEBUG] starting service creation monitor")
for {
select {
case p := <-s.commandCreatedChan:
if p != nil && p.Process != nil {
s.processMap.Set(p.Process.Pid, p)
}
}
}
}
|
go
|
func (s *ServiceManager) addServiceMonitor() {
log.Println("[DEBUG] starting service creation monitor")
for {
select {
case p := <-s.commandCreatedChan:
if p != nil && p.Process != nil {
s.processMap.Set(p.Process.Pid, p)
}
}
}
}
|
[
"func",
"(",
"s",
"*",
"ServiceManager",
")",
"addServiceMonitor",
"(",
")",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] starting service creation monitor\"",
")",
"\n",
"for",
"{",
"select",
"{",
"case",
"p",
":=",
"<-",
"s",
".",
"commandCreatedChan",
":",
"if",
"p",
"!=",
"nil",
"&&",
"p",
".",
"Process",
"!=",
"nil",
"{",
"s",
".",
"processMap",
".",
"Set",
"(",
"p",
".",
"Process",
".",
"Pid",
",",
"p",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// addServiceMonitor watches a channel to add services into operation.
|
[
"addServiceMonitor",
"watches",
"a",
"channel",
"to",
"add",
"services",
"into",
"operation",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L36-L46
|
test
|
pact-foundation/pact-go
|
client/service_manager.go
|
removeServiceMonitor
|
func (s *ServiceManager) removeServiceMonitor() {
log.Println("[DEBUG] starting service removal monitor")
var p *exec.Cmd
for {
select {
case p = <-s.commandCompleteChan:
if p != nil && p.Process != nil {
p.Process.Signal(os.Interrupt)
s.processMap.Delete(p.Process.Pid)
}
}
}
}
|
go
|
func (s *ServiceManager) removeServiceMonitor() {
log.Println("[DEBUG] starting service removal monitor")
var p *exec.Cmd
for {
select {
case p = <-s.commandCompleteChan:
if p != nil && p.Process != nil {
p.Process.Signal(os.Interrupt)
s.processMap.Delete(p.Process.Pid)
}
}
}
}
|
[
"func",
"(",
"s",
"*",
"ServiceManager",
")",
"removeServiceMonitor",
"(",
")",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] starting service removal monitor\"",
")",
"\n",
"var",
"p",
"*",
"exec",
".",
"Cmd",
"\n",
"for",
"{",
"select",
"{",
"case",
"p",
"=",
"<-",
"s",
".",
"commandCompleteChan",
":",
"if",
"p",
"!=",
"nil",
"&&",
"p",
".",
"Process",
"!=",
"nil",
"{",
"p",
".",
"Process",
".",
"Signal",
"(",
"os",
".",
"Interrupt",
")",
"\n",
"s",
".",
"processMap",
".",
"Delete",
"(",
"p",
".",
"Process",
".",
"Pid",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// removeServiceMonitor watches a channel to remove services from operation.
|
[
"removeServiceMonitor",
"watches",
"a",
"channel",
"to",
"remove",
"services",
"from",
"operation",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L49-L61
|
test
|
pact-foundation/pact-go
|
client/service_manager.go
|
List
|
func (s *ServiceManager) List() map[int]*exec.Cmd {
log.Println("[DEBUG] listing services")
return s.processMap.processes
}
|
go
|
func (s *ServiceManager) List() map[int]*exec.Cmd {
log.Println("[DEBUG] listing services")
return s.processMap.processes
}
|
[
"func",
"(",
"s",
"*",
"ServiceManager",
")",
"List",
"(",
")",
"map",
"[",
"int",
"]",
"*",
"exec",
".",
"Cmd",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] listing services\"",
")",
"\n",
"return",
"s",
".",
"processMap",
".",
"processes",
"\n",
"}"
] |
// List all Service PIDs.
|
[
"List",
"all",
"Service",
"PIDs",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L98-L101
|
test
|
pact-foundation/pact-go
|
client/service_manager.go
|
Command
|
func (s *ServiceManager) Command() *exec.Cmd {
cmd := exec.Command(s.Cmd, s.Args...)
env := os.Environ()
env = append(env, s.Env...)
cmd.Env = env
return cmd
}
|
go
|
func (s *ServiceManager) Command() *exec.Cmd {
cmd := exec.Command(s.Cmd, s.Args...)
env := os.Environ()
env = append(env, s.Env...)
cmd.Env = env
return cmd
}
|
[
"func",
"(",
"s",
"*",
"ServiceManager",
")",
"Command",
"(",
")",
"*",
"exec",
".",
"Cmd",
"{",
"cmd",
":=",
"exec",
".",
"Command",
"(",
"s",
".",
"Cmd",
",",
"s",
".",
"Args",
"...",
")",
"\n",
"env",
":=",
"os",
".",
"Environ",
"(",
")",
"\n",
"env",
"=",
"append",
"(",
"env",
",",
"s",
".",
"Env",
"...",
")",
"\n",
"cmd",
".",
"Env",
"=",
"env",
"\n",
"return",
"cmd",
"\n",
"}"
] |
// Command creates an os command to be run
|
[
"Command",
"creates",
"an",
"os",
"command",
"to",
"be",
"run"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/client/service_manager.go#L104-L111
|
test
|
pact-foundation/pact-go
|
dsl/mock_service.go
|
call
|
func (m *MockService) call(method string, url string, content interface{}) error {
body, err := json.Marshal(content)
if err != nil {
fmt.Println(err)
return err
}
client := &http.Client{}
var req *http.Request
if method == "POST" {
req, err = http.NewRequest(method, url, bytes.NewReader(body))
} else {
req, err = http.NewRequest(method, url, nil)
}
if err != nil {
return err
}
req.Header.Set("X-Pact-Mock-Service", "true")
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return err
}
responseBody, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return errors.New(string(responseBody))
}
return err
}
|
go
|
func (m *MockService) call(method string, url string, content interface{}) error {
body, err := json.Marshal(content)
if err != nil {
fmt.Println(err)
return err
}
client := &http.Client{}
var req *http.Request
if method == "POST" {
req, err = http.NewRequest(method, url, bytes.NewReader(body))
} else {
req, err = http.NewRequest(method, url, nil)
}
if err != nil {
return err
}
req.Header.Set("X-Pact-Mock-Service", "true")
req.Header.Set("Content-Type", "application/json")
res, err := client.Do(req)
if err != nil {
return err
}
responseBody, err := ioutil.ReadAll(res.Body)
res.Body.Close()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return errors.New(string(responseBody))
}
return err
}
|
[
"func",
"(",
"m",
"*",
"MockService",
")",
"call",
"(",
"method",
"string",
",",
"url",
"string",
",",
"content",
"interface",
"{",
"}",
")",
"error",
"{",
"body",
",",
"err",
":=",
"json",
".",
"Marshal",
"(",
"content",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"fmt",
".",
"Println",
"(",
"err",
")",
"\n",
"return",
"err",
"\n",
"}",
"\n",
"client",
":=",
"&",
"http",
".",
"Client",
"{",
"}",
"\n",
"var",
"req",
"*",
"http",
".",
"Request",
"\n",
"if",
"method",
"==",
"\"POST\"",
"{",
"req",
",",
"err",
"=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"bytes",
".",
"NewReader",
"(",
"body",
")",
")",
"\n",
"}",
"else",
"{",
"req",
",",
"err",
"=",
"http",
".",
"NewRequest",
"(",
"method",
",",
"url",
",",
"nil",
")",
"\n",
"}",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"X-Pact-Mock-Service\"",
",",
"\"true\"",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"Content-Type\"",
",",
"\"application/json\"",
")",
"\n",
"res",
",",
"err",
":=",
"client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"responseBody",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"res",
".",
"Body",
")",
"\n",
"res",
".",
"Body",
".",
"Close",
"(",
")",
"\n",
"if",
"res",
".",
"StatusCode",
"<",
"200",
"||",
"res",
".",
"StatusCode",
">=",
"300",
"{",
"return",
"errors",
".",
"New",
"(",
"string",
"(",
"responseBody",
")",
")",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// call sends a message to the Pact service
|
[
"call",
"sends",
"a",
"message",
"to",
"the",
"Pact",
"service"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L36-L68
|
test
|
pact-foundation/pact-go
|
dsl/mock_service.go
|
DeleteInteractions
|
func (m *MockService) DeleteInteractions() error {
log.Println("[DEBUG] mock service delete interactions")
url := fmt.Sprintf("%s/interactions", m.BaseURL)
return m.call("DELETE", url, nil)
}
|
go
|
func (m *MockService) DeleteInteractions() error {
log.Println("[DEBUG] mock service delete interactions")
url := fmt.Sprintf("%s/interactions", m.BaseURL)
return m.call("DELETE", url, nil)
}
|
[
"func",
"(",
"m",
"*",
"MockService",
")",
"DeleteInteractions",
"(",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] mock service delete interactions\"",
")",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/interactions\"",
",",
"m",
".",
"BaseURL",
")",
"\n",
"return",
"m",
".",
"call",
"(",
"\"DELETE\"",
",",
"url",
",",
"nil",
")",
"\n",
"}"
] |
// DeleteInteractions removes any previous Mock Service Interactions.
|
[
"DeleteInteractions",
"removes",
"any",
"previous",
"Mock",
"Service",
"Interactions",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L71-L75
|
test
|
pact-foundation/pact-go
|
dsl/mock_service.go
|
AddInteraction
|
func (m *MockService) AddInteraction(interaction *Interaction) error {
log.Println("[DEBUG] mock service add interaction")
url := fmt.Sprintf("%s/interactions", m.BaseURL)
return m.call("POST", url, interaction)
}
|
go
|
func (m *MockService) AddInteraction(interaction *Interaction) error {
log.Println("[DEBUG] mock service add interaction")
url := fmt.Sprintf("%s/interactions", m.BaseURL)
return m.call("POST", url, interaction)
}
|
[
"func",
"(",
"m",
"*",
"MockService",
")",
"AddInteraction",
"(",
"interaction",
"*",
"Interaction",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] mock service add interaction\"",
")",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/interactions\"",
",",
"m",
".",
"BaseURL",
")",
"\n",
"return",
"m",
".",
"call",
"(",
"\"POST\"",
",",
"url",
",",
"interaction",
")",
"\n",
"}"
] |
// AddInteraction adds a new Pact Mock Service interaction.
|
[
"AddInteraction",
"adds",
"a",
"new",
"Pact",
"Mock",
"Service",
"interaction",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L78-L82
|
test
|
pact-foundation/pact-go
|
dsl/mock_service.go
|
WritePact
|
func (m *MockService) WritePact() error {
log.Println("[DEBUG] mock service write pact")
if m.Consumer == "" || m.Provider == "" {
return errors.New("Consumer and Provider name need to be provided")
}
if m.PactFileWriteMode == "" {
m.PactFileWriteMode = "overwrite"
}
pact := map[string]interface{}{
"consumer": map[string]string{
"name": m.Consumer,
},
"provider": map[string]string{
"name": m.Provider,
},
"pactFileWriteMode": m.PactFileWriteMode,
}
url := fmt.Sprintf("%s/pact", m.BaseURL)
return m.call("POST", url, pact)
}
|
go
|
func (m *MockService) WritePact() error {
log.Println("[DEBUG] mock service write pact")
if m.Consumer == "" || m.Provider == "" {
return errors.New("Consumer and Provider name need to be provided")
}
if m.PactFileWriteMode == "" {
m.PactFileWriteMode = "overwrite"
}
pact := map[string]interface{}{
"consumer": map[string]string{
"name": m.Consumer,
},
"provider": map[string]string{
"name": m.Provider,
},
"pactFileWriteMode": m.PactFileWriteMode,
}
url := fmt.Sprintf("%s/pact", m.BaseURL)
return m.call("POST", url, pact)
}
|
[
"func",
"(",
"m",
"*",
"MockService",
")",
"WritePact",
"(",
")",
"error",
"{",
"log",
".",
"Println",
"(",
"\"[DEBUG] mock service write pact\"",
")",
"\n",
"if",
"m",
".",
"Consumer",
"==",
"\"\"",
"||",
"m",
".",
"Provider",
"==",
"\"\"",
"{",
"return",
"errors",
".",
"New",
"(",
"\"Consumer and Provider name need to be provided\"",
")",
"\n",
"}",
"\n",
"if",
"m",
".",
"PactFileWriteMode",
"==",
"\"\"",
"{",
"m",
".",
"PactFileWriteMode",
"=",
"\"overwrite\"",
"\n",
"}",
"\n",
"pact",
":=",
"map",
"[",
"string",
"]",
"interface",
"{",
"}",
"{",
"\"consumer\"",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"\"name\"",
":",
"m",
".",
"Consumer",
",",
"}",
",",
"\"provider\"",
":",
"map",
"[",
"string",
"]",
"string",
"{",
"\"name\"",
":",
"m",
".",
"Provider",
",",
"}",
",",
"\"pactFileWriteMode\"",
":",
"m",
".",
"PactFileWriteMode",
",",
"}",
"\n",
"url",
":=",
"fmt",
".",
"Sprintf",
"(",
"\"%s/pact\"",
",",
"m",
".",
"BaseURL",
")",
"\n",
"return",
"m",
".",
"call",
"(",
"\"POST\"",
",",
"url",
",",
"pact",
")",
"\n",
"}"
] |
// WritePact writes the pact file to disk.
|
[
"WritePact",
"writes",
"the",
"pact",
"file",
"to",
"disk",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/mock_service.go#L92-L114
|
test
|
pact-foundation/pact-go
|
dsl/message.go
|
ExpectsToReceive
|
func (p *Message) ExpectsToReceive(description string) *Message {
p.Description = description
return p
}
|
go
|
func (p *Message) ExpectsToReceive(description string) *Message {
p.Description = description
return p
}
|
[
"func",
"(",
"p",
"*",
"Message",
")",
"ExpectsToReceive",
"(",
"description",
"string",
")",
"*",
"Message",
"{",
"p",
".",
"Description",
"=",
"description",
"\n",
"return",
"p",
"\n",
"}"
] |
// ExpectsToReceive specifies the content it is expecting to be
// given from the Provider. The function must be able to handle this
// message for the interaction to succeed.
|
[
"ExpectsToReceive",
"specifies",
"the",
"content",
"it",
"is",
"expecting",
"to",
"be",
"given",
"from",
"the",
"Provider",
".",
"The",
"function",
"must",
"be",
"able",
"to",
"handle",
"this",
"message",
"for",
"the",
"interaction",
"to",
"succeed",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L69-L72
|
test
|
pact-foundation/pact-go
|
dsl/message.go
|
WithMetadata
|
func (p *Message) WithMetadata(metadata MapMatcher) *Message {
p.Metadata = metadata
return p
}
|
go
|
func (p *Message) WithMetadata(metadata MapMatcher) *Message {
p.Metadata = metadata
return p
}
|
[
"func",
"(",
"p",
"*",
"Message",
")",
"WithMetadata",
"(",
"metadata",
"MapMatcher",
")",
"*",
"Message",
"{",
"p",
".",
"Metadata",
"=",
"metadata",
"\n",
"return",
"p",
"\n",
"}"
] |
// WithMetadata specifies message-implementation specific metadata
// to go with the content
|
[
"WithMetadata",
"specifies",
"message",
"-",
"implementation",
"specific",
"metadata",
"to",
"go",
"with",
"the",
"content"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L76-L79
|
test
|
pact-foundation/pact-go
|
dsl/message.go
|
AsType
|
func (p *Message) AsType(t interface{}) *Message {
fmt.Println("[DEBUG] setting Message decoding to type:", reflect.TypeOf(t))
p.Type = t
return p
}
|
go
|
func (p *Message) AsType(t interface{}) *Message {
fmt.Println("[DEBUG] setting Message decoding to type:", reflect.TypeOf(t))
p.Type = t
return p
}
|
[
"func",
"(",
"p",
"*",
"Message",
")",
"AsType",
"(",
"t",
"interface",
"{",
"}",
")",
"*",
"Message",
"{",
"fmt",
".",
"Println",
"(",
"\"[DEBUG] setting Message decoding to type:\"",
",",
"reflect",
".",
"TypeOf",
"(",
"t",
")",
")",
"\n",
"p",
".",
"Type",
"=",
"t",
"\n",
"return",
"p",
"\n",
"}"
] |
// AsType specifies that the content sent through to the
// consumer handler should be sent as the given type
|
[
"AsType",
"specifies",
"that",
"the",
"content",
"sent",
"through",
"to",
"the",
"consumer",
"handler",
"should",
"be",
"sent",
"as",
"the",
"given",
"type"
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/dsl/message.go#L92-L97
|
test
|
pact-foundation/pact-go
|
examples/gin/provider/user_service.go
|
UserLogin
|
func UserLogin(c *gin.Context) {
c.Header("X-Api-Correlation-Id", "1234")
var json Login
if c.BindJSON(&json) == nil {
user, err := userRepository.ByUsername(json.User)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"status": "file not found"})
} else if user.Username != json.User || user.Password != json.Password {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
} else {
c.Header("X-Auth-Token", getAuthToken())
c.JSON(http.StatusOK, types.LoginResponse{User: user})
}
}
}
|
go
|
func UserLogin(c *gin.Context) {
c.Header("X-Api-Correlation-Id", "1234")
var json Login
if c.BindJSON(&json) == nil {
user, err := userRepository.ByUsername(json.User)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"status": "file not found"})
} else if user.Username != json.User || user.Password != json.Password {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
} else {
c.Header("X-Auth-Token", getAuthToken())
c.JSON(http.StatusOK, types.LoginResponse{User: user})
}
}
}
|
[
"func",
"UserLogin",
"(",
"c",
"*",
"gin",
".",
"Context",
")",
"{",
"c",
".",
"Header",
"(",
"\"X-Api-Correlation-Id\"",
",",
"\"1234\"",
")",
"\n",
"var",
"json",
"Login",
"\n",
"if",
"c",
".",
"BindJSON",
"(",
"&",
"json",
")",
"==",
"nil",
"{",
"user",
",",
"err",
":=",
"userRepository",
".",
"ByUsername",
"(",
"json",
".",
"User",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"c",
".",
"JSON",
"(",
"http",
".",
"StatusNotFound",
",",
"gin",
".",
"H",
"{",
"\"status\"",
":",
"\"file not found\"",
"}",
")",
"\n",
"}",
"else",
"if",
"user",
".",
"Username",
"!=",
"json",
".",
"User",
"||",
"user",
".",
"Password",
"!=",
"json",
".",
"Password",
"{",
"c",
".",
"JSON",
"(",
"http",
".",
"StatusUnauthorized",
",",
"gin",
".",
"H",
"{",
"\"status\"",
":",
"\"unauthorized\"",
"}",
")",
"\n",
"}",
"else",
"{",
"c",
".",
"Header",
"(",
"\"X-Auth-Token\"",
",",
"getAuthToken",
"(",
")",
")",
"\n",
"c",
".",
"JSON",
"(",
"http",
".",
"StatusOK",
",",
"types",
".",
"LoginResponse",
"{",
"User",
":",
"user",
"}",
")",
"\n",
"}",
"\n",
"}",
"\n",
"}"
] |
// UserLogin is the login route.
|
[
"UserLogin",
"is",
"the",
"login",
"route",
"."
] |
467dea56d27e154363e1975f6e9f4dbf66148e79
|
https://github.com/pact-foundation/pact-go/blob/467dea56d27e154363e1975f6e9f4dbf66148e79/examples/gin/provider/user_service.go#L50-L65
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
Region
|
func (s *S3) Region() string {
region := os.Getenv("AWS_REGION")
switch s.Domain {
case "s3.amazonaws.com", "s3-external-1.amazonaws.com":
return "us-east-1"
case "s3-accelerate.amazonaws.com":
if region == "" {
panic("can't find endpoint region")
}
return region
default:
regions := regionMatcher.FindStringSubmatch(s.Domain)
if len(regions) < 2 {
if region == "" {
panic("can't find endpoint region")
}
return region
}
return regions[1]
}
}
|
go
|
func (s *S3) Region() string {
region := os.Getenv("AWS_REGION")
switch s.Domain {
case "s3.amazonaws.com", "s3-external-1.amazonaws.com":
return "us-east-1"
case "s3-accelerate.amazonaws.com":
if region == "" {
panic("can't find endpoint region")
}
return region
default:
regions := regionMatcher.FindStringSubmatch(s.Domain)
if len(regions) < 2 {
if region == "" {
panic("can't find endpoint region")
}
return region
}
return regions[1]
}
}
|
[
"func",
"(",
"s",
"*",
"S3",
")",
"Region",
"(",
")",
"string",
"{",
"region",
":=",
"os",
".",
"Getenv",
"(",
"\"AWS_REGION\"",
")",
"\n",
"switch",
"s",
".",
"Domain",
"{",
"case",
"\"s3.amazonaws.com\"",
",",
"\"s3-external-1.amazonaws.com\"",
":",
"return",
"\"us-east-1\"",
"\n",
"case",
"\"s3-accelerate.amazonaws.com\"",
":",
"if",
"region",
"==",
"\"\"",
"{",
"panic",
"(",
"\"can't find endpoint region\"",
")",
"\n",
"}",
"\n",
"return",
"region",
"\n",
"default",
":",
"regions",
":=",
"regionMatcher",
".",
"FindStringSubmatch",
"(",
"s",
".",
"Domain",
")",
"\n",
"if",
"len",
"(",
"regions",
")",
"<",
"2",
"{",
"if",
"region",
"==",
"\"\"",
"{",
"panic",
"(",
"\"can't find endpoint region\"",
")",
"\n",
"}",
"\n",
"return",
"region",
"\n",
"}",
"\n",
"return",
"regions",
"[",
"1",
"]",
"\n",
"}",
"\n",
"}"
] |
// Region returns the service region infering it from S3 domain.
|
[
"Region",
"returns",
"the",
"service",
"region",
"infering",
"it",
"from",
"S3",
"domain",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L31-L51
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
New
|
func New(domain string, keys Keys) *S3 {
if domain == "" {
domain = DefaultDomain
}
return &S3{domain, keys}
}
|
go
|
func New(domain string, keys Keys) *S3 {
if domain == "" {
domain = DefaultDomain
}
return &S3{domain, keys}
}
|
[
"func",
"New",
"(",
"domain",
"string",
",",
"keys",
"Keys",
")",
"*",
"S3",
"{",
"if",
"domain",
"==",
"\"\"",
"{",
"domain",
"=",
"DefaultDomain",
"\n",
"}",
"\n",
"return",
"&",
"S3",
"{",
"domain",
",",
"keys",
"}",
"\n",
"}"
] |
// New Returns a new S3
// domain defaults to DefaultDomain if empty
|
[
"New",
"Returns",
"a",
"new",
"S3",
"domain",
"defaults",
"to",
"DefaultDomain",
"if",
"empty"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L90-L95
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
Bucket
|
func (s *S3) Bucket(name string) *Bucket {
return &Bucket{
S3: s,
Name: name,
Config: DefaultConfig,
}
}
|
go
|
func (s *S3) Bucket(name string) *Bucket {
return &Bucket{
S3: s,
Name: name,
Config: DefaultConfig,
}
}
|
[
"func",
"(",
"s",
"*",
"S3",
")",
"Bucket",
"(",
"name",
"string",
")",
"*",
"Bucket",
"{",
"return",
"&",
"Bucket",
"{",
"S3",
":",
"s",
",",
"Name",
":",
"name",
",",
"Config",
":",
"DefaultConfig",
",",
"}",
"\n",
"}"
] |
// Bucket returns a bucket on s3
// Bucket Config is initialized to DefaultConfig
|
[
"Bucket",
"returns",
"a",
"bucket",
"on",
"s3",
"Bucket",
"Config",
"is",
"initialized",
"to",
"DefaultConfig"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L99-L105
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
PutWriter
|
func (b *Bucket) PutWriter(path string, h http.Header, c *Config) (w io.WriteCloser, err error) {
if c == nil {
c = b.conf()
}
u, err := b.url(path, c)
if err != nil {
return nil, err
}
return newPutter(*u, h, c, b)
}
|
go
|
func (b *Bucket) PutWriter(path string, h http.Header, c *Config) (w io.WriteCloser, err error) {
if c == nil {
c = b.conf()
}
u, err := b.url(path, c)
if err != nil {
return nil, err
}
return newPutter(*u, h, c, b)
}
|
[
"func",
"(",
"b",
"*",
"Bucket",
")",
"PutWriter",
"(",
"path",
"string",
",",
"h",
"http",
".",
"Header",
",",
"c",
"*",
"Config",
")",
"(",
"w",
"io",
".",
"WriteCloser",
",",
"err",
"error",
")",
"{",
"if",
"c",
"==",
"nil",
"{",
"c",
"=",
"b",
".",
"conf",
"(",
")",
"\n",
"}",
"\n",
"u",
",",
"err",
":=",
"b",
".",
"url",
"(",
"path",
",",
"c",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"return",
"newPutter",
"(",
"*",
"u",
",",
"h",
",",
"c",
",",
"b",
")",
"\n",
"}"
] |
// PutWriter provides a writer to upload data as multipart upload requests.
//
// Each header in h is added to the HTTP request header. This is useful for specifying
// options such as server-side encryption in metadata as well as custom user metadata.
// DefaultConfig is used if c is nil.
// Callers should call Close on w to ensure that all resources are released.
|
[
"PutWriter",
"provides",
"a",
"writer",
"to",
"upload",
"data",
"as",
"multipart",
"upload",
"requests",
".",
"Each",
"header",
"in",
"h",
"is",
"added",
"to",
"the",
"HTTP",
"request",
"header",
".",
"This",
"is",
"useful",
"for",
"specifying",
"options",
"such",
"as",
"server",
"-",
"side",
"encryption",
"in",
"metadata",
"as",
"well",
"as",
"custom",
"user",
"metadata",
".",
"DefaultConfig",
"is",
"used",
"if",
"c",
"is",
"nil",
".",
"Callers",
"should",
"call",
"Close",
"on",
"w",
"to",
"ensure",
"that",
"all",
"resources",
"are",
"released",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L136-L146
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
url
|
func (b *Bucket) url(bPath string, c *Config) (*url.URL, error) {
// parse versionID parameter from path, if included
// See https://github.com/rlmcpherson/s3gof3r/issues/84 for rationale
purl, err := url.Parse(bPath)
if err != nil {
return nil, err
}
var vals url.Values
if v := purl.Query().Get(versionParam); v != "" {
vals = make(url.Values)
vals.Add(versionParam, v)
bPath = strings.Split(bPath, "?")[0] // remove versionID from path
}
// handling for bucket names containing periods / explicit PathStyle addressing
// http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html for details
if strings.Contains(b.Name, ".") || c.PathStyle {
return &url.URL{
Host: b.S3.Domain,
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s/%s", b.Name, bPath)),
RawQuery: vals.Encode(),
}, nil
} else {
return &url.URL{
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s", bPath)),
Host: path.Clean(fmt.Sprintf("%s.%s", b.Name, b.S3.Domain)),
RawQuery: vals.Encode(),
}, nil
}
}
|
go
|
func (b *Bucket) url(bPath string, c *Config) (*url.URL, error) {
// parse versionID parameter from path, if included
// See https://github.com/rlmcpherson/s3gof3r/issues/84 for rationale
purl, err := url.Parse(bPath)
if err != nil {
return nil, err
}
var vals url.Values
if v := purl.Query().Get(versionParam); v != "" {
vals = make(url.Values)
vals.Add(versionParam, v)
bPath = strings.Split(bPath, "?")[0] // remove versionID from path
}
// handling for bucket names containing periods / explicit PathStyle addressing
// http://docs.aws.amazon.com/AmazonS3/latest/dev/BucketRestrictions.html for details
if strings.Contains(b.Name, ".") || c.PathStyle {
return &url.URL{
Host: b.S3.Domain,
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s/%s", b.Name, bPath)),
RawQuery: vals.Encode(),
}, nil
} else {
return &url.URL{
Scheme: c.Scheme,
Path: path.Clean(fmt.Sprintf("/%s", bPath)),
Host: path.Clean(fmt.Sprintf("%s.%s", b.Name, b.S3.Domain)),
RawQuery: vals.Encode(),
}, nil
}
}
|
[
"func",
"(",
"b",
"*",
"Bucket",
")",
"url",
"(",
"bPath",
"string",
",",
"c",
"*",
"Config",
")",
"(",
"*",
"url",
".",
"URL",
",",
"error",
")",
"{",
"purl",
",",
"err",
":=",
"url",
".",
"Parse",
"(",
"bPath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"nil",
",",
"err",
"\n",
"}",
"\n",
"var",
"vals",
"url",
".",
"Values",
"\n",
"if",
"v",
":=",
"purl",
".",
"Query",
"(",
")",
".",
"Get",
"(",
"versionParam",
")",
";",
"v",
"!=",
"\"\"",
"{",
"vals",
"=",
"make",
"(",
"url",
".",
"Values",
")",
"\n",
"vals",
".",
"Add",
"(",
"versionParam",
",",
"v",
")",
"\n",
"bPath",
"=",
"strings",
".",
"Split",
"(",
"bPath",
",",
"\"?\"",
")",
"[",
"0",
"]",
"\n",
"}",
"\n",
"if",
"strings",
".",
"Contains",
"(",
"b",
".",
"Name",
",",
"\".\"",
")",
"||",
"c",
".",
"PathStyle",
"{",
"return",
"&",
"url",
".",
"URL",
"{",
"Host",
":",
"b",
".",
"S3",
".",
"Domain",
",",
"Scheme",
":",
"c",
".",
"Scheme",
",",
"Path",
":",
"path",
".",
"Clean",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"/%s/%s\"",
",",
"b",
".",
"Name",
",",
"bPath",
")",
")",
",",
"RawQuery",
":",
"vals",
".",
"Encode",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}",
"else",
"{",
"return",
"&",
"url",
".",
"URL",
"{",
"Scheme",
":",
"c",
".",
"Scheme",
",",
"Path",
":",
"path",
".",
"Clean",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"/%s\"",
",",
"bPath",
")",
")",
",",
"Host",
":",
"path",
".",
"Clean",
"(",
"fmt",
".",
"Sprintf",
"(",
"\"%s.%s\"",
",",
"b",
".",
"Name",
",",
"b",
".",
"S3",
".",
"Domain",
")",
")",
",",
"RawQuery",
":",
"vals",
".",
"Encode",
"(",
")",
",",
"}",
",",
"nil",
"\n",
"}",
"\n",
"}"
] |
// url returns a parsed url to the given path. c must not be nil
|
[
"url",
"returns",
"a",
"parsed",
"url",
"to",
"the",
"given",
"path",
".",
"c",
"must",
"not",
"be",
"nil"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L149-L181
|
test
|
rlmcpherson/s3gof3r
|
s3gof3r.go
|
SetLogger
|
func SetLogger(out io.Writer, prefix string, flag int, debug bool) {
logger = internalLogger{
log.New(out, prefix, flag),
debug,
}
}
|
go
|
func SetLogger(out io.Writer, prefix string, flag int, debug bool) {
logger = internalLogger{
log.New(out, prefix, flag),
debug,
}
}
|
[
"func",
"SetLogger",
"(",
"out",
"io",
".",
"Writer",
",",
"prefix",
"string",
",",
"flag",
"int",
",",
"debug",
"bool",
")",
"{",
"logger",
"=",
"internalLogger",
"{",
"log",
".",
"New",
"(",
"out",
",",
"prefix",
",",
"flag",
")",
",",
"debug",
",",
"}",
"\n",
"}"
] |
// SetLogger wraps the standard library log package.
//
// It allows the internal logging of s3gof3r to be set to a desired output and format.
// Setting debug to true enables debug logging output. s3gof3r does not log output by default.
|
[
"SetLogger",
"wraps",
"the",
"standard",
"library",
"log",
"package",
".",
"It",
"allows",
"the",
"internal",
"logging",
"of",
"s3gof3r",
"to",
"be",
"set",
"to",
"a",
"desired",
"output",
"and",
"format",
".",
"Setting",
"debug",
"to",
"true",
"enables",
"debug",
"logging",
"output",
".",
"s3gof3r",
"does",
"not",
"log",
"output",
"by",
"default",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/s3gof3r.go#L233-L238
|
test
|
rlmcpherson/s3gof3r
|
auth.go
|
InstanceKeys
|
func InstanceKeys() (keys Keys, err error) {
rolePath := "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
var creds mdCreds
// request the role name for the instance
// assumes there is only one
resp, err := ClientWithTimeout(2 * time.Second).Get(rolePath)
if err != nil {
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
err = newRespError(resp)
return
}
role, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// request the credential metadata for the role
resp, err = http.Get(rolePath + string(role))
if err != nil {
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
err = newRespError(resp)
return
}
metadata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = json.Unmarshal([]byte(metadata), &creds); err != nil {
return
}
keys = Keys{
AccessKey: creds.AccessKeyID,
SecretKey: creds.SecretAccessKey,
SecurityToken: creds.Token,
}
return
}
|
go
|
func InstanceKeys() (keys Keys, err error) {
rolePath := "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
var creds mdCreds
// request the role name for the instance
// assumes there is only one
resp, err := ClientWithTimeout(2 * time.Second).Get(rolePath)
if err != nil {
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
err = newRespError(resp)
return
}
role, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
// request the credential metadata for the role
resp, err = http.Get(rolePath + string(role))
if err != nil {
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
err = newRespError(resp)
return
}
metadata, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err = json.Unmarshal([]byte(metadata), &creds); err != nil {
return
}
keys = Keys{
AccessKey: creds.AccessKeyID,
SecretKey: creds.SecretAccessKey,
SecurityToken: creds.Token,
}
return
}
|
[
"func",
"InstanceKeys",
"(",
")",
"(",
"keys",
"Keys",
",",
"err",
"error",
")",
"{",
"rolePath",
":=",
"\"http://169.254.169.254/latest/meta-data/iam/security-credentials/\"",
"\n",
"var",
"creds",
"mdCreds",
"\n",
"resp",
",",
"err",
":=",
"ClientWithTimeout",
"(",
"2",
"*",
"time",
".",
"Second",
")",
".",
"Get",
"(",
"rolePath",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"checkClose",
"(",
"resp",
".",
"Body",
",",
"err",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"err",
"=",
"newRespError",
"(",
"resp",
")",
"\n",
"return",
"\n",
"}",
"\n",
"role",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"resp",
",",
"err",
"=",
"http",
".",
"Get",
"(",
"rolePath",
"+",
"string",
"(",
"role",
")",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"defer",
"checkClose",
"(",
"resp",
".",
"Body",
",",
"err",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"err",
"=",
"newRespError",
"(",
"resp",
")",
"\n",
"return",
"\n",
"}",
"\n",
"metadata",
",",
"err",
":=",
"ioutil",
".",
"ReadAll",
"(",
"resp",
".",
"Body",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"if",
"err",
"=",
"json",
".",
"Unmarshal",
"(",
"[",
"]",
"byte",
"(",
"metadata",
")",
",",
"&",
"creds",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"keys",
"=",
"Keys",
"{",
"AccessKey",
":",
"creds",
".",
"AccessKeyID",
",",
"SecretKey",
":",
"creds",
".",
"SecretAccessKey",
",",
"SecurityToken",
":",
"creds",
".",
"Token",
",",
"}",
"\n",
"return",
"\n",
"}"
] |
// InstanceKeys Requests the AWS keys from the instance-based metadata on EC2
// Assumes only one IAM role.
|
[
"InstanceKeys",
"Requests",
"the",
"AWS",
"keys",
"from",
"the",
"instance",
"-",
"based",
"metadata",
"on",
"EC2",
"Assumes",
"only",
"one",
"IAM",
"role",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/auth.go#L32-L79
|
test
|
rlmcpherson/s3gof3r
|
auth.go
|
EnvKeys
|
func EnvKeys() (keys Keys, err error) {
keys = Keys{
AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"),
SecretKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),
SecurityToken: os.Getenv("AWS_SECURITY_TOKEN"),
}
if keys.AccessKey == "" || keys.SecretKey == "" {
err = fmt.Errorf("keys not set in environment: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY")
}
return
}
|
go
|
func EnvKeys() (keys Keys, err error) {
keys = Keys{
AccessKey: os.Getenv("AWS_ACCESS_KEY_ID"),
SecretKey: os.Getenv("AWS_SECRET_ACCESS_KEY"),
SecurityToken: os.Getenv("AWS_SECURITY_TOKEN"),
}
if keys.AccessKey == "" || keys.SecretKey == "" {
err = fmt.Errorf("keys not set in environment: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY")
}
return
}
|
[
"func",
"EnvKeys",
"(",
")",
"(",
"keys",
"Keys",
",",
"err",
"error",
")",
"{",
"keys",
"=",
"Keys",
"{",
"AccessKey",
":",
"os",
".",
"Getenv",
"(",
"\"AWS_ACCESS_KEY_ID\"",
")",
",",
"SecretKey",
":",
"os",
".",
"Getenv",
"(",
"\"AWS_SECRET_ACCESS_KEY\"",
")",
",",
"SecurityToken",
":",
"os",
".",
"Getenv",
"(",
"\"AWS_SECURITY_TOKEN\"",
")",
",",
"}",
"\n",
"if",
"keys",
".",
"AccessKey",
"==",
"\"\"",
"||",
"keys",
".",
"SecretKey",
"==",
"\"\"",
"{",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"keys not set in environment: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY\"",
")",
"\n",
"}",
"\n",
"return",
"\n",
"}"
] |
// EnvKeys Reads the AWS keys from the environment
|
[
"EnvKeys",
"Reads",
"the",
"AWS",
"keys",
"from",
"the",
"environment"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/auth.go#L82-L92
|
test
|
rlmcpherson/s3gof3r
|
sign.go
|
Sign
|
func (b *Bucket) Sign(req *http.Request) {
if req.Header == nil {
req.Header = http.Header{}
}
if b.S3.Keys.SecurityToken != "" {
req.Header.Set("X-Amz-Security-Token", b.S3.Keys.SecurityToken)
}
req.Header.Set("User-Agent", "S3Gof3r")
s := &signer{
Time: time.Now(),
Request: req,
Region: b.S3.Region(),
Keys: b.S3.Keys,
}
s.sign()
}
|
go
|
func (b *Bucket) Sign(req *http.Request) {
if req.Header == nil {
req.Header = http.Header{}
}
if b.S3.Keys.SecurityToken != "" {
req.Header.Set("X-Amz-Security-Token", b.S3.Keys.SecurityToken)
}
req.Header.Set("User-Agent", "S3Gof3r")
s := &signer{
Time: time.Now(),
Request: req,
Region: b.S3.Region(),
Keys: b.S3.Keys,
}
s.sign()
}
|
[
"func",
"(",
"b",
"*",
"Bucket",
")",
"Sign",
"(",
"req",
"*",
"http",
".",
"Request",
")",
"{",
"if",
"req",
".",
"Header",
"==",
"nil",
"{",
"req",
".",
"Header",
"=",
"http",
".",
"Header",
"{",
"}",
"\n",
"}",
"\n",
"if",
"b",
".",
"S3",
".",
"Keys",
".",
"SecurityToken",
"!=",
"\"\"",
"{",
"req",
".",
"Header",
".",
"Set",
"(",
"\"X-Amz-Security-Token\"",
",",
"b",
".",
"S3",
".",
"Keys",
".",
"SecurityToken",
")",
"\n",
"}",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"\"User-Agent\"",
",",
"\"S3Gof3r\"",
")",
"\n",
"s",
":=",
"&",
"signer",
"{",
"Time",
":",
"time",
".",
"Now",
"(",
")",
",",
"Request",
":",
"req",
",",
"Region",
":",
"b",
".",
"S3",
".",
"Region",
"(",
")",
",",
"Keys",
":",
"b",
".",
"S3",
".",
"Keys",
",",
"}",
"\n",
"s",
".",
"sign",
"(",
")",
"\n",
"}"
] |
// Sign signs the http.Request
|
[
"Sign",
"signs",
"the",
"http",
".",
"Request"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/sign.go#L45-L60
|
test
|
rlmcpherson/s3gof3r
|
gof3r/main.go
|
getAWSKeys
|
func getAWSKeys() (keys s3gof3r.Keys, err error) {
keys, err = s3gof3r.EnvKeys()
if err == nil {
return
}
keys, err = s3gof3r.InstanceKeys()
if err == nil {
return
}
err = errors.New("no AWS keys found")
return
}
|
go
|
func getAWSKeys() (keys s3gof3r.Keys, err error) {
keys, err = s3gof3r.EnvKeys()
if err == nil {
return
}
keys, err = s3gof3r.InstanceKeys()
if err == nil {
return
}
err = errors.New("no AWS keys found")
return
}
|
[
"func",
"getAWSKeys",
"(",
")",
"(",
"keys",
"s3gof3r",
".",
"Keys",
",",
"err",
"error",
")",
"{",
"keys",
",",
"err",
"=",
"s3gof3r",
".",
"EnvKeys",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"keys",
",",
"err",
"=",
"s3gof3r",
".",
"InstanceKeys",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"{",
"return",
"\n",
"}",
"\n",
"err",
"=",
"errors",
".",
"New",
"(",
"\"no AWS keys found\"",
")",
"\n",
"return",
"\n",
"}"
] |
// getAWSKeys gets the AWS Keys from environment variables or the instance-based metadata on EC2
// Environment variables are attempted first, followed by the instance-based credentials.
|
[
"getAWSKeys",
"gets",
"the",
"AWS",
"Keys",
"from",
"environment",
"variables",
"or",
"the",
"instance",
"-",
"based",
"metadata",
"on",
"EC2",
"Environment",
"variables",
"are",
"attempted",
"first",
"followed",
"by",
"the",
"instance",
"-",
"based",
"credentials",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/gof3r/main.go#L89-L101
|
test
|
rlmcpherson/s3gof3r
|
gof3r/options.go
|
homeDir
|
func homeDir() (string, error) {
if h := os.Getenv("HOME"); h != "" {
return h, nil
}
h, err := exec.Command("sh", "-c", "eval echo ~$USER").Output()
if err == nil && len(h) > 0 {
return strings.TrimSpace(string(h)), nil
}
return "", fmt.Errorf("home directory not found for current user")
}
|
go
|
func homeDir() (string, error) {
if h := os.Getenv("HOME"); h != "" {
return h, nil
}
h, err := exec.Command("sh", "-c", "eval echo ~$USER").Output()
if err == nil && len(h) > 0 {
return strings.TrimSpace(string(h)), nil
}
return "", fmt.Errorf("home directory not found for current user")
}
|
[
"func",
"homeDir",
"(",
")",
"(",
"string",
",",
"error",
")",
"{",
"if",
"h",
":=",
"os",
".",
"Getenv",
"(",
"\"HOME\"",
")",
";",
"h",
"!=",
"\"\"",
"{",
"return",
"h",
",",
"nil",
"\n",
"}",
"\n",
"h",
",",
"err",
":=",
"exec",
".",
"Command",
"(",
"\"sh\"",
",",
"\"-c\"",
",",
"\"eval echo ~$USER\"",
")",
".",
"Output",
"(",
")",
"\n",
"if",
"err",
"==",
"nil",
"&&",
"len",
"(",
"h",
")",
">",
"0",
"{",
"return",
"strings",
".",
"TrimSpace",
"(",
"string",
"(",
"h",
")",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"\"\"",
",",
"fmt",
".",
"Errorf",
"(",
"\"home directory not found for current user\"",
")",
"\n",
"}"
] |
// find unix home directory
|
[
"find",
"unix",
"home",
"directory"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/gof3r/options.go#L105-L114
|
test
|
rlmcpherson/s3gof3r
|
gof3r/options.go
|
ACL
|
func ACL(h http.Header, acl string) http.Header {
if acl != "" {
h.Set("x-amz-acl", acl)
}
return h
}
|
go
|
func ACL(h http.Header, acl string) http.Header {
if acl != "" {
h.Set("x-amz-acl", acl)
}
return h
}
|
[
"func",
"ACL",
"(",
"h",
"http",
".",
"Header",
",",
"acl",
"string",
")",
"http",
".",
"Header",
"{",
"if",
"acl",
"!=",
"\"\"",
"{",
"h",
".",
"Set",
"(",
"\"x-amz-acl\"",
",",
"acl",
")",
"\n",
"}",
"\n",
"return",
"h",
"\n",
"}"
] |
// add canned acl to http.Header
|
[
"add",
"canned",
"acl",
"to",
"http",
".",
"Header"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/gof3r/options.go#L117-L122
|
test
|
rlmcpherson/s3gof3r
|
putter.go
|
putPart
|
func (p *putter) putPart(part *part) error {
v := url.Values{}
v.Set("partNumber", strconv.Itoa(part.PartNumber))
v.Set("uploadId", p.UploadID)
if _, err := part.r.Seek(0, 0); err != nil { // move back to beginning, if retrying
return err
}
req, err := http.NewRequest("PUT", p.url.String()+"?"+v.Encode(), part.r)
if err != nil {
return err
}
req.ContentLength = part.len
req.Header.Set(md5Header, part.md5)
req.Header.Set(sha256Header, part.sha256)
p.b.Sign(req)
resp, err := p.c.Client.Do(req)
if err != nil {
return err
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return newRespError(resp)
}
s := resp.Header.Get("etag")
if len(s) < 2 {
return fmt.Errorf("Got Bad etag:%s", s)
}
s = s[1 : len(s)-1] // includes quote chars for some reason
if part.ETag != s {
return fmt.Errorf("Response etag does not match. Remote:%s Calculated:%s", s, p.ETag)
}
return nil
}
|
go
|
func (p *putter) putPart(part *part) error {
v := url.Values{}
v.Set("partNumber", strconv.Itoa(part.PartNumber))
v.Set("uploadId", p.UploadID)
if _, err := part.r.Seek(0, 0); err != nil { // move back to beginning, if retrying
return err
}
req, err := http.NewRequest("PUT", p.url.String()+"?"+v.Encode(), part.r)
if err != nil {
return err
}
req.ContentLength = part.len
req.Header.Set(md5Header, part.md5)
req.Header.Set(sha256Header, part.sha256)
p.b.Sign(req)
resp, err := p.c.Client.Do(req)
if err != nil {
return err
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 200 {
return newRespError(resp)
}
s := resp.Header.Get("etag")
if len(s) < 2 {
return fmt.Errorf("Got Bad etag:%s", s)
}
s = s[1 : len(s)-1] // includes quote chars for some reason
if part.ETag != s {
return fmt.Errorf("Response etag does not match. Remote:%s Calculated:%s", s, p.ETag)
}
return nil
}
|
[
"func",
"(",
"p",
"*",
"putter",
")",
"putPart",
"(",
"part",
"*",
"part",
")",
"error",
"{",
"v",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"v",
".",
"Set",
"(",
"\"partNumber\"",
",",
"strconv",
".",
"Itoa",
"(",
"part",
".",
"PartNumber",
")",
")",
"\n",
"v",
".",
"Set",
"(",
"\"uploadId\"",
",",
"p",
".",
"UploadID",
")",
"\n",
"if",
"_",
",",
"err",
":=",
"part",
".",
"r",
".",
"Seek",
"(",
"0",
",",
"0",
")",
";",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
",",
"err",
":=",
"http",
".",
"NewRequest",
"(",
"\"PUT\"",
",",
"p",
".",
"url",
".",
"String",
"(",
")",
"+",
"\"?\"",
"+",
"v",
".",
"Encode",
"(",
")",
",",
"part",
".",
"r",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"req",
".",
"ContentLength",
"=",
"part",
".",
"len",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"md5Header",
",",
"part",
".",
"md5",
")",
"\n",
"req",
".",
"Header",
".",
"Set",
"(",
"sha256Header",
",",
"part",
".",
"sha256",
")",
"\n",
"p",
".",
"b",
".",
"Sign",
"(",
"req",
")",
"\n",
"resp",
",",
"err",
":=",
"p",
".",
"c",
".",
"Client",
".",
"Do",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"defer",
"checkClose",
"(",
"resp",
".",
"Body",
",",
"err",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"200",
"{",
"return",
"newRespError",
"(",
"resp",
")",
"\n",
"}",
"\n",
"s",
":=",
"resp",
".",
"Header",
".",
"Get",
"(",
"\"etag\"",
")",
"\n",
"if",
"len",
"(",
"s",
")",
"<",
"2",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Got Bad etag:%s\"",
",",
"s",
")",
"\n",
"}",
"\n",
"s",
"=",
"s",
"[",
"1",
":",
"len",
"(",
"s",
")",
"-",
"1",
"]",
"\n",
"if",
"part",
".",
"ETag",
"!=",
"s",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"Response etag does not match. Remote:%s Calculated:%s\"",
",",
"s",
",",
"p",
".",
"ETag",
")",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// uploads a part, checking the etag against the calculated value
|
[
"uploads",
"a",
"part",
"checking",
"the",
"etag",
"against",
"the",
"calculated",
"value"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/putter.go#L194-L226
|
test
|
rlmcpherson/s3gof3r
|
putter.go
|
abort
|
func (p *putter) abort() {
v := url.Values{}
v.Set("uploadId", p.UploadID)
s := p.url.String() + "?" + v.Encode()
resp, err := p.retryRequest("DELETE", s, nil, nil)
if err != nil {
logger.Printf("Error aborting multipart upload: %v\n", err)
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 204 {
logger.Printf("Error aborting multipart upload: %v", newRespError(resp))
}
return
}
|
go
|
func (p *putter) abort() {
v := url.Values{}
v.Set("uploadId", p.UploadID)
s := p.url.String() + "?" + v.Encode()
resp, err := p.retryRequest("DELETE", s, nil, nil)
if err != nil {
logger.Printf("Error aborting multipart upload: %v\n", err)
return
}
defer checkClose(resp.Body, err)
if resp.StatusCode != 204 {
logger.Printf("Error aborting multipart upload: %v", newRespError(resp))
}
return
}
|
[
"func",
"(",
"p",
"*",
"putter",
")",
"abort",
"(",
")",
"{",
"v",
":=",
"url",
".",
"Values",
"{",
"}",
"\n",
"v",
".",
"Set",
"(",
"\"uploadId\"",
",",
"p",
".",
"UploadID",
")",
"\n",
"s",
":=",
"p",
".",
"url",
".",
"String",
"(",
")",
"+",
"\"?\"",
"+",
"v",
".",
"Encode",
"(",
")",
"\n",
"resp",
",",
"err",
":=",
"p",
".",
"retryRequest",
"(",
"\"DELETE\"",
",",
"s",
",",
"nil",
",",
"nil",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"logger",
".",
"Printf",
"(",
"\"Error aborting multipart upload: %v\\n\"",
",",
"\\n",
")",
"\n",
"err",
"\n",
"}",
"\n",
"return",
"\n",
"defer",
"checkClose",
"(",
"resp",
".",
"Body",
",",
"err",
")",
"\n",
"if",
"resp",
".",
"StatusCode",
"!=",
"204",
"{",
"logger",
".",
"Printf",
"(",
"\"Error aborting multipart upload: %v\"",
",",
"newRespError",
"(",
"resp",
")",
")",
"\n",
"}",
"\n",
"}"
] |
// Try to abort multipart upload. Do not error on failure.
|
[
"Try",
"to",
"abort",
"multipart",
"upload",
".",
"Do",
"not",
"error",
"on",
"failure",
"."
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/putter.go#L302-L316
|
test
|
rlmcpherson/s3gof3r
|
putter.go
|
growPartSize
|
func growPartSize(partIndex int, partSize, putsz int64) bool {
return (maxObjSize-putsz)/(maxNPart-int64(partIndex)) > partSize
}
|
go
|
func growPartSize(partIndex int, partSize, putsz int64) bool {
return (maxObjSize-putsz)/(maxNPart-int64(partIndex)) > partSize
}
|
[
"func",
"growPartSize",
"(",
"partIndex",
"int",
",",
"partSize",
",",
"putsz",
"int64",
")",
"bool",
"{",
"return",
"(",
"maxObjSize",
"-",
"putsz",
")",
"/",
"(",
"maxNPart",
"-",
"int64",
"(",
"partIndex",
")",
")",
">",
"partSize",
"\n",
"}"
] |
// returns true unless partSize is large enough
// to achieve maxObjSize with remaining parts
|
[
"returns",
"true",
"unless",
"partSize",
"is",
"large",
"enough",
"to",
"achieve",
"maxObjSize",
"with",
"remaining",
"parts"
] |
864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14
|
https://github.com/rlmcpherson/s3gof3r/blob/864ae0bf7cf2e20c0002b7ea17f4d84fec1abc14/putter.go#L399-L401
|
test
|
kelseyhightower/envconfig
|
envconfig.go
|
CheckDisallowed
|
func CheckDisallowed(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}
vars := make(map[string]struct{})
for _, info := range infos {
vars[info.Key] = struct{}{}
}
if prefix != "" {
prefix = strings.ToUpper(prefix) + "_"
}
for _, env := range os.Environ() {
if !strings.HasPrefix(env, prefix) {
continue
}
v := strings.SplitN(env, "=", 2)[0]
if _, found := vars[v]; !found {
return fmt.Errorf("unknown environment variable %s", v)
}
}
return nil
}
|
go
|
func CheckDisallowed(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}
vars := make(map[string]struct{})
for _, info := range infos {
vars[info.Key] = struct{}{}
}
if prefix != "" {
prefix = strings.ToUpper(prefix) + "_"
}
for _, env := range os.Environ() {
if !strings.HasPrefix(env, prefix) {
continue
}
v := strings.SplitN(env, "=", 2)[0]
if _, found := vars[v]; !found {
return fmt.Errorf("unknown environment variable %s", v)
}
}
return nil
}
|
[
"func",
"CheckDisallowed",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
")",
"error",
"{",
"infos",
",",
"err",
":=",
"gatherInfo",
"(",
"prefix",
",",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"vars",
":=",
"make",
"(",
"map",
"[",
"string",
"]",
"struct",
"{",
"}",
")",
"\n",
"for",
"_",
",",
"info",
":=",
"range",
"infos",
"{",
"vars",
"[",
"info",
".",
"Key",
"]",
"=",
"struct",
"{",
"}",
"{",
"}",
"\n",
"}",
"\n",
"if",
"prefix",
"!=",
"\"\"",
"{",
"prefix",
"=",
"strings",
".",
"ToUpper",
"(",
"prefix",
")",
"+",
"\"_\"",
"\n",
"}",
"\n",
"for",
"_",
",",
"env",
":=",
"range",
"os",
".",
"Environ",
"(",
")",
"{",
"if",
"!",
"strings",
".",
"HasPrefix",
"(",
"env",
",",
"prefix",
")",
"{",
"continue",
"\n",
"}",
"\n",
"v",
":=",
"strings",
".",
"SplitN",
"(",
"env",
",",
"\"=\"",
",",
"2",
")",
"[",
"0",
"]",
"\n",
"if",
"_",
",",
"found",
":=",
"vars",
"[",
"v",
"]",
";",
"!",
"found",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"unknown environment variable %s\"",
",",
"v",
")",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"nil",
"\n",
"}"
] |
// CheckDisallowed checks that no environment variables with the prefix are set
// that we don't know how or want to parse. This is likely only meaningful with
// a non-empty prefix.
|
[
"CheckDisallowed",
"checks",
"that",
"no",
"environment",
"variables",
"with",
"the",
"prefix",
"are",
"set",
"that",
"we",
"don",
"t",
"know",
"how",
"or",
"want",
"to",
"parse",
".",
"This",
"is",
"likely",
"only",
"meaningful",
"with",
"a",
"non",
"-",
"empty",
"prefix",
"."
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L150-L176
|
test
|
kelseyhightower/envconfig
|
envconfig.go
|
Process
|
func Process(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
for _, info := range infos {
// `os.Getenv` cannot differentiate between an explicitly set empty value
// and an unset value. `os.LookupEnv` is preferred to `syscall.Getenv`,
// but it is only available in go1.5 or newer. We're using Go build tags
// here to use os.LookupEnv for >=go1.5
value, ok := lookupEnv(info.Key)
if !ok && info.Alt != "" {
value, ok = lookupEnv(info.Alt)
}
def := info.Tags.Get("default")
if def != "" && !ok {
value = def
}
req := info.Tags.Get("required")
if !ok && def == "" {
if isTrue(req) {
return fmt.Errorf("required key %s missing value", info.Key)
}
continue
}
err = processField(value, info.Field)
if err != nil {
return &ParseError{
KeyName: info.Key,
FieldName: info.Name,
TypeName: info.Field.Type().String(),
Value: value,
Err: err,
}
}
}
return err
}
|
go
|
func Process(prefix string, spec interface{}) error {
infos, err := gatherInfo(prefix, spec)
for _, info := range infos {
// `os.Getenv` cannot differentiate between an explicitly set empty value
// and an unset value. `os.LookupEnv` is preferred to `syscall.Getenv`,
// but it is only available in go1.5 or newer. We're using Go build tags
// here to use os.LookupEnv for >=go1.5
value, ok := lookupEnv(info.Key)
if !ok && info.Alt != "" {
value, ok = lookupEnv(info.Alt)
}
def := info.Tags.Get("default")
if def != "" && !ok {
value = def
}
req := info.Tags.Get("required")
if !ok && def == "" {
if isTrue(req) {
return fmt.Errorf("required key %s missing value", info.Key)
}
continue
}
err = processField(value, info.Field)
if err != nil {
return &ParseError{
KeyName: info.Key,
FieldName: info.Name,
TypeName: info.Field.Type().String(),
Value: value,
Err: err,
}
}
}
return err
}
|
[
"func",
"Process",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
")",
"error",
"{",
"infos",
",",
"err",
":=",
"gatherInfo",
"(",
"prefix",
",",
"spec",
")",
"\n",
"for",
"_",
",",
"info",
":=",
"range",
"infos",
"{",
"value",
",",
"ok",
":=",
"lookupEnv",
"(",
"info",
".",
"Key",
")",
"\n",
"if",
"!",
"ok",
"&&",
"info",
".",
"Alt",
"!=",
"\"\"",
"{",
"value",
",",
"ok",
"=",
"lookupEnv",
"(",
"info",
".",
"Alt",
")",
"\n",
"}",
"\n",
"def",
":=",
"info",
".",
"Tags",
".",
"Get",
"(",
"\"default\"",
")",
"\n",
"if",
"def",
"!=",
"\"\"",
"&&",
"!",
"ok",
"{",
"value",
"=",
"def",
"\n",
"}",
"\n",
"req",
":=",
"info",
".",
"Tags",
".",
"Get",
"(",
"\"required\"",
")",
"\n",
"if",
"!",
"ok",
"&&",
"def",
"==",
"\"\"",
"{",
"if",
"isTrue",
"(",
"req",
")",
"{",
"return",
"fmt",
".",
"Errorf",
"(",
"\"required key %s missing value\"",
",",
"info",
".",
"Key",
")",
"\n",
"}",
"\n",
"continue",
"\n",
"}",
"\n",
"err",
"=",
"processField",
"(",
"value",
",",
"info",
".",
"Field",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"&",
"ParseError",
"{",
"KeyName",
":",
"info",
".",
"Key",
",",
"FieldName",
":",
"info",
".",
"Name",
",",
"TypeName",
":",
"info",
".",
"Field",
".",
"Type",
"(",
")",
".",
"String",
"(",
")",
",",
"Value",
":",
"value",
",",
"Err",
":",
"err",
",",
"}",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"err",
"\n",
"}"
] |
// Process populates the specified struct based on environment variables
|
[
"Process",
"populates",
"the",
"specified",
"struct",
"based",
"on",
"environment",
"variables"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L179-L219
|
test
|
kelseyhightower/envconfig
|
envconfig.go
|
MustProcess
|
func MustProcess(prefix string, spec interface{}) {
if err := Process(prefix, spec); err != nil {
panic(err)
}
}
|
go
|
func MustProcess(prefix string, spec interface{}) {
if err := Process(prefix, spec); err != nil {
panic(err)
}
}
|
[
"func",
"MustProcess",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
")",
"{",
"if",
"err",
":=",
"Process",
"(",
"prefix",
",",
"spec",
")",
";",
"err",
"!=",
"nil",
"{",
"panic",
"(",
"err",
")",
"\n",
"}",
"\n",
"}"
] |
// MustProcess is the same as Process but panics if an error occurs
|
[
"MustProcess",
"is",
"the",
"same",
"as",
"Process",
"but",
"panics",
"if",
"an",
"error",
"occurs"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/envconfig.go#L222-L226
|
test
|
kelseyhightower/envconfig
|
usage.go
|
toTypeDescription
|
func toTypeDescription(t reflect.Type) string {
switch t.Kind() {
case reflect.Array, reflect.Slice:
return fmt.Sprintf("Comma-separated list of %s", toTypeDescription(t.Elem()))
case reflect.Map:
return fmt.Sprintf(
"Comma-separated list of %s:%s pairs",
toTypeDescription(t.Key()),
toTypeDescription(t.Elem()),
)
case reflect.Ptr:
return toTypeDescription(t.Elem())
case reflect.Struct:
if implementsInterface(t) && t.Name() != "" {
return t.Name()
}
return ""
case reflect.String:
name := t.Name()
if name != "" && name != "string" {
return name
}
return "String"
case reflect.Bool:
name := t.Name()
if name != "" && name != "bool" {
return name
}
return "True or False"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "int") {
return name
}
return "Integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "uint") {
return name
}
return "Unsigned Integer"
case reflect.Float32, reflect.Float64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "float") {
return name
}
return "Float"
}
return fmt.Sprintf("%+v", t)
}
|
go
|
func toTypeDescription(t reflect.Type) string {
switch t.Kind() {
case reflect.Array, reflect.Slice:
return fmt.Sprintf("Comma-separated list of %s", toTypeDescription(t.Elem()))
case reflect.Map:
return fmt.Sprintf(
"Comma-separated list of %s:%s pairs",
toTypeDescription(t.Key()),
toTypeDescription(t.Elem()),
)
case reflect.Ptr:
return toTypeDescription(t.Elem())
case reflect.Struct:
if implementsInterface(t) && t.Name() != "" {
return t.Name()
}
return ""
case reflect.String:
name := t.Name()
if name != "" && name != "string" {
return name
}
return "String"
case reflect.Bool:
name := t.Name()
if name != "" && name != "bool" {
return name
}
return "True or False"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "int") {
return name
}
return "Integer"
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "uint") {
return name
}
return "Unsigned Integer"
case reflect.Float32, reflect.Float64:
name := t.Name()
if name != "" && !strings.HasPrefix(name, "float") {
return name
}
return "Float"
}
return fmt.Sprintf("%+v", t)
}
|
[
"func",
"toTypeDescription",
"(",
"t",
"reflect",
".",
"Type",
")",
"string",
"{",
"switch",
"t",
".",
"Kind",
"(",
")",
"{",
"case",
"reflect",
".",
"Array",
",",
"reflect",
".",
"Slice",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"Comma-separated list of %s\"",
",",
"toTypeDescription",
"(",
"t",
".",
"Elem",
"(",
")",
")",
")",
"\n",
"case",
"reflect",
".",
"Map",
":",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"Comma-separated list of %s:%s pairs\"",
",",
"toTypeDescription",
"(",
"t",
".",
"Key",
"(",
")",
")",
",",
"toTypeDescription",
"(",
"t",
".",
"Elem",
"(",
")",
")",
",",
")",
"\n",
"case",
"reflect",
".",
"Ptr",
":",
"return",
"toTypeDescription",
"(",
"t",
".",
"Elem",
"(",
")",
")",
"\n",
"case",
"reflect",
".",
"Struct",
":",
"if",
"implementsInterface",
"(",
"t",
")",
"&&",
"t",
".",
"Name",
"(",
")",
"!=",
"\"\"",
"{",
"return",
"t",
".",
"Name",
"(",
")",
"\n",
"}",
"\n",
"return",
"\"\"",
"\n",
"case",
"reflect",
".",
"String",
":",
"name",
":=",
"t",
".",
"Name",
"(",
")",
"\n",
"if",
"name",
"!=",
"\"\"",
"&&",
"name",
"!=",
"\"string\"",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"\"String\"",
"\n",
"case",
"reflect",
".",
"Bool",
":",
"name",
":=",
"t",
".",
"Name",
"(",
")",
"\n",
"if",
"name",
"!=",
"\"\"",
"&&",
"name",
"!=",
"\"bool\"",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"\"True or False\"",
"\n",
"case",
"reflect",
".",
"Int",
",",
"reflect",
".",
"Int8",
",",
"reflect",
".",
"Int16",
",",
"reflect",
".",
"Int32",
",",
"reflect",
".",
"Int64",
":",
"name",
":=",
"t",
".",
"Name",
"(",
")",
"\n",
"if",
"name",
"!=",
"\"\"",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"int\"",
")",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"\"Integer\"",
"\n",
"case",
"reflect",
".",
"Uint",
",",
"reflect",
".",
"Uint8",
",",
"reflect",
".",
"Uint16",
",",
"reflect",
".",
"Uint32",
",",
"reflect",
".",
"Uint64",
":",
"name",
":=",
"t",
".",
"Name",
"(",
")",
"\n",
"if",
"name",
"!=",
"\"\"",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"uint\"",
")",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"\"Unsigned Integer\"",
"\n",
"case",
"reflect",
".",
"Float32",
",",
"reflect",
".",
"Float64",
":",
"name",
":=",
"t",
".",
"Name",
"(",
")",
"\n",
"if",
"name",
"!=",
"\"\"",
"&&",
"!",
"strings",
".",
"HasPrefix",
"(",
"name",
",",
"\"float\"",
")",
"{",
"return",
"name",
"\n",
"}",
"\n",
"return",
"\"Float\"",
"\n",
"}",
"\n",
"return",
"fmt",
".",
"Sprintf",
"(",
"\"%+v\"",
",",
"t",
")",
"\n",
"}"
] |
// toTypeDescription converts Go types into a human readable description
|
[
"toTypeDescription",
"converts",
"Go",
"types",
"into",
"a",
"human",
"readable",
"description"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L58-L107
|
test
|
kelseyhightower/envconfig
|
usage.go
|
Usage
|
func Usage(prefix string, spec interface{}) error {
// The default is to output the usage information as a table
// Create tabwriter instance to support table output
tabs := tabwriter.NewWriter(os.Stdout, 1, 0, 4, ' ', 0)
err := Usagef(prefix, spec, tabs, DefaultTableFormat)
tabs.Flush()
return err
}
|
go
|
func Usage(prefix string, spec interface{}) error {
// The default is to output the usage information as a table
// Create tabwriter instance to support table output
tabs := tabwriter.NewWriter(os.Stdout, 1, 0, 4, ' ', 0)
err := Usagef(prefix, spec, tabs, DefaultTableFormat)
tabs.Flush()
return err
}
|
[
"func",
"Usage",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
")",
"error",
"{",
"tabs",
":=",
"tabwriter",
".",
"NewWriter",
"(",
"os",
".",
"Stdout",
",",
"1",
",",
"0",
",",
"4",
",",
"' '",
",",
"0",
")",
"\n",
"err",
":=",
"Usagef",
"(",
"prefix",
",",
"spec",
",",
"tabs",
",",
"DefaultTableFormat",
")",
"\n",
"tabs",
".",
"Flush",
"(",
")",
"\n",
"return",
"err",
"\n",
"}"
] |
// Usage writes usage information to stderr using the default header and table format
|
[
"Usage",
"writes",
"usage",
"information",
"to",
"stderr",
"using",
"the",
"default",
"header",
"and",
"table",
"format"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L110-L118
|
test
|
kelseyhightower/envconfig
|
usage.go
|
Usagef
|
func Usagef(prefix string, spec interface{}, out io.Writer, format string) error {
// Specify the default usage template functions
functions := template.FuncMap{
"usage_key": func(v varInfo) string { return v.Key },
"usage_description": func(v varInfo) string { return v.Tags.Get("desc") },
"usage_type": func(v varInfo) string { return toTypeDescription(v.Field.Type()) },
"usage_default": func(v varInfo) string { return v.Tags.Get("default") },
"usage_required": func(v varInfo) (string, error) {
req := v.Tags.Get("required")
if req != "" {
reqB, err := strconv.ParseBool(req)
if err != nil {
return "", err
}
if reqB {
req = "true"
}
}
return req, nil
},
}
tmpl, err := template.New("envconfig").Funcs(functions).Parse(format)
if err != nil {
return err
}
return Usaget(prefix, spec, out, tmpl)
}
|
go
|
func Usagef(prefix string, spec interface{}, out io.Writer, format string) error {
// Specify the default usage template functions
functions := template.FuncMap{
"usage_key": func(v varInfo) string { return v.Key },
"usage_description": func(v varInfo) string { return v.Tags.Get("desc") },
"usage_type": func(v varInfo) string { return toTypeDescription(v.Field.Type()) },
"usage_default": func(v varInfo) string { return v.Tags.Get("default") },
"usage_required": func(v varInfo) (string, error) {
req := v.Tags.Get("required")
if req != "" {
reqB, err := strconv.ParseBool(req)
if err != nil {
return "", err
}
if reqB {
req = "true"
}
}
return req, nil
},
}
tmpl, err := template.New("envconfig").Funcs(functions).Parse(format)
if err != nil {
return err
}
return Usaget(prefix, spec, out, tmpl)
}
|
[
"func",
"Usagef",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
",",
"out",
"io",
".",
"Writer",
",",
"format",
"string",
")",
"error",
"{",
"functions",
":=",
"template",
".",
"FuncMap",
"{",
"\"usage_key\"",
":",
"func",
"(",
"v",
"varInfo",
")",
"string",
"{",
"return",
"v",
".",
"Key",
"}",
",",
"\"usage_description\"",
":",
"func",
"(",
"v",
"varInfo",
")",
"string",
"{",
"return",
"v",
".",
"Tags",
".",
"Get",
"(",
"\"desc\"",
")",
"}",
",",
"\"usage_type\"",
":",
"func",
"(",
"v",
"varInfo",
")",
"string",
"{",
"return",
"toTypeDescription",
"(",
"v",
".",
"Field",
".",
"Type",
"(",
")",
")",
"}",
",",
"\"usage_default\"",
":",
"func",
"(",
"v",
"varInfo",
")",
"string",
"{",
"return",
"v",
".",
"Tags",
".",
"Get",
"(",
"\"default\"",
")",
"}",
",",
"\"usage_required\"",
":",
"func",
"(",
"v",
"varInfo",
")",
"(",
"string",
",",
"error",
")",
"{",
"req",
":=",
"v",
".",
"Tags",
".",
"Get",
"(",
"\"required\"",
")",
"\n",
"if",
"req",
"!=",
"\"\"",
"{",
"reqB",
",",
"err",
":=",
"strconv",
".",
"ParseBool",
"(",
"req",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"\"\"",
",",
"err",
"\n",
"}",
"\n",
"if",
"reqB",
"{",
"req",
"=",
"\"true\"",
"\n",
"}",
"\n",
"}",
"\n",
"return",
"req",
",",
"nil",
"\n",
"}",
",",
"}",
"\n",
"tmpl",
",",
"err",
":=",
"template",
".",
"New",
"(",
"\"envconfig\"",
")",
".",
"Funcs",
"(",
"functions",
")",
".",
"Parse",
"(",
"format",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"Usaget",
"(",
"prefix",
",",
"spec",
",",
"out",
",",
"tmpl",
")",
"\n",
"}"
] |
// Usagef writes usage information to the specified io.Writer using the specifed template specification
|
[
"Usagef",
"writes",
"usage",
"information",
"to",
"the",
"specified",
"io",
".",
"Writer",
"using",
"the",
"specifed",
"template",
"specification"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L121-L150
|
test
|
kelseyhightower/envconfig
|
usage.go
|
Usaget
|
func Usaget(prefix string, spec interface{}, out io.Writer, tmpl *template.Template) error {
// gather first
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}
return tmpl.Execute(out, infos)
}
|
go
|
func Usaget(prefix string, spec interface{}, out io.Writer, tmpl *template.Template) error {
// gather first
infos, err := gatherInfo(prefix, spec)
if err != nil {
return err
}
return tmpl.Execute(out, infos)
}
|
[
"func",
"Usaget",
"(",
"prefix",
"string",
",",
"spec",
"interface",
"{",
"}",
",",
"out",
"io",
".",
"Writer",
",",
"tmpl",
"*",
"template",
".",
"Template",
")",
"error",
"{",
"infos",
",",
"err",
":=",
"gatherInfo",
"(",
"prefix",
",",
"spec",
")",
"\n",
"if",
"err",
"!=",
"nil",
"{",
"return",
"err",
"\n",
"}",
"\n",
"return",
"tmpl",
".",
"Execute",
"(",
"out",
",",
"infos",
")",
"\n",
"}"
] |
// Usaget writes usage information to the specified io.Writer using the specified template
|
[
"Usaget",
"writes",
"usage",
"information",
"to",
"the",
"specified",
"io",
".",
"Writer",
"using",
"the",
"specified",
"template"
] |
dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1
|
https://github.com/kelseyhightower/envconfig/blob/dd1402a4d99de9ac2f396cd6fcb957bc2c695ec1/usage.go#L153-L161
|
test
|
guregu/null
|
time.go
|
Scan
|
func (t *Time) Scan(value interface{}) error {
var err error
switch x := value.(type) {
case time.Time:
t.Time = x
case nil:
t.Valid = false
return nil
default:
err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value)
}
t.Valid = err == nil
return err
}
|
go
|
func (t *Time) Scan(value interface{}) error {
var err error
switch x := value.(type) {
case time.Time:
t.Time = x
case nil:
t.Valid = false
return nil
default:
err = fmt.Errorf("null: cannot scan type %T into null.Time: %v", value, value)
}
t.Valid = err == nil
return err
}
|
[
"func",
"(",
"t",
"*",
"Time",
")",
"Scan",
"(",
"value",
"interface",
"{",
"}",
")",
"error",
"{",
"var",
"err",
"error",
"\n",
"switch",
"x",
":=",
"value",
".",
"(",
"type",
")",
"{",
"case",
"time",
".",
"Time",
":",
"t",
".",
"Time",
"=",
"x",
"\n",
"case",
"nil",
":",
"t",
".",
"Valid",
"=",
"false",
"\n",
"return",
"nil",
"\n",
"default",
":",
"err",
"=",
"fmt",
".",
"Errorf",
"(",
"\"null: cannot scan type %T into null.Time: %v\"",
",",
"value",
",",
"value",
")",
"\n",
"}",
"\n",
"t",
".",
"Valid",
"=",
"err",
"==",
"nil",
"\n",
"return",
"err",
"\n",
"}"
] |
// Scan implements the Scanner interface.
|
[
"Scan",
"implements",
"the",
"Scanner",
"interface",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L19-L32
|
test
|
guregu/null
|
time.go
|
Value
|
func (t Time) Value() (driver.Value, error) {
if !t.Valid {
return nil, nil
}
return t.Time, nil
}
|
go
|
func (t Time) Value() (driver.Value, error) {
if !t.Valid {
return nil, nil
}
return t.Time, nil
}
|
[
"func",
"(",
"t",
"Time",
")",
"Value",
"(",
")",
"(",
"driver",
".",
"Value",
",",
"error",
")",
"{",
"if",
"!",
"t",
".",
"Valid",
"{",
"return",
"nil",
",",
"nil",
"\n",
"}",
"\n",
"return",
"t",
".",
"Time",
",",
"nil",
"\n",
"}"
] |
// Value implements the driver Valuer interface.
|
[
"Value",
"implements",
"the",
"driver",
"Valuer",
"interface",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L35-L40
|
test
|
guregu/null
|
time.go
|
NewTime
|
func NewTime(t time.Time, valid bool) Time {
return Time{
Time: t,
Valid: valid,
}
}
|
go
|
func NewTime(t time.Time, valid bool) Time {
return Time{
Time: t,
Valid: valid,
}
}
|
[
"func",
"NewTime",
"(",
"t",
"time",
".",
"Time",
",",
"valid",
"bool",
")",
"Time",
"{",
"return",
"Time",
"{",
"Time",
":",
"t",
",",
"Valid",
":",
"valid",
",",
"}",
"\n",
"}"
] |
// NewTime creates a new Time.
|
[
"NewTime",
"creates",
"a",
"new",
"Time",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L43-L48
|
test
|
guregu/null
|
time.go
|
TimeFromPtr
|
func TimeFromPtr(t *time.Time) Time {
if t == nil {
return NewTime(time.Time{}, false)
}
return NewTime(*t, true)
}
|
go
|
func TimeFromPtr(t *time.Time) Time {
if t == nil {
return NewTime(time.Time{}, false)
}
return NewTime(*t, true)
}
|
[
"func",
"TimeFromPtr",
"(",
"t",
"*",
"time",
".",
"Time",
")",
"Time",
"{",
"if",
"t",
"==",
"nil",
"{",
"return",
"NewTime",
"(",
"time",
".",
"Time",
"{",
"}",
",",
"false",
")",
"\n",
"}",
"\n",
"return",
"NewTime",
"(",
"*",
"t",
",",
"true",
")",
"\n",
"}"
] |
// TimeFromPtr creates a new Time that will be null if t is nil.
|
[
"TimeFromPtr",
"creates",
"a",
"new",
"Time",
"that",
"will",
"be",
"null",
"if",
"t",
"is",
"nil",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L56-L61
|
test
|
guregu/null
|
time.go
|
ValueOrZero
|
func (t Time) ValueOrZero() time.Time {
if !t.Valid {
return time.Time{}
}
return t.Time
}
|
go
|
func (t Time) ValueOrZero() time.Time {
if !t.Valid {
return time.Time{}
}
return t.Time
}
|
[
"func",
"(",
"t",
"Time",
")",
"ValueOrZero",
"(",
")",
"time",
".",
"Time",
"{",
"if",
"!",
"t",
".",
"Valid",
"{",
"return",
"time",
".",
"Time",
"{",
"}",
"\n",
"}",
"\n",
"return",
"t",
".",
"Time",
"\n",
"}"
] |
// ValueOrZero returns the inner value if valid, otherwise zero.
|
[
"ValueOrZero",
"returns",
"the",
"inner",
"value",
"if",
"valid",
"otherwise",
"zero",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L64-L69
|
test
|
guregu/null
|
time.go
|
MarshalJSON
|
func (t Time) MarshalJSON() ([]byte, error) {
if !t.Valid {
return []byte("null"), nil
}
return t.Time.MarshalJSON()
}
|
go
|
func (t Time) MarshalJSON() ([]byte, error) {
if !t.Valid {
return []byte("null"), nil
}
return t.Time.MarshalJSON()
}
|
[
"func",
"(",
"t",
"Time",
")",
"MarshalJSON",
"(",
")",
"(",
"[",
"]",
"byte",
",",
"error",
")",
"{",
"if",
"!",
"t",
".",
"Valid",
"{",
"return",
"[",
"]",
"byte",
"(",
"\"null\"",
")",
",",
"nil",
"\n",
"}",
"\n",
"return",
"t",
".",
"Time",
".",
"MarshalJSON",
"(",
")",
"\n",
"}"
] |
// MarshalJSON implements json.Marshaler.
// It will encode null if this time is null.
|
[
"MarshalJSON",
"implements",
"json",
".",
"Marshaler",
".",
"It",
"will",
"encode",
"null",
"if",
"this",
"time",
"is",
"null",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L73-L78
|
test
|
guregu/null
|
time.go
|
SetValid
|
func (t *Time) SetValid(v time.Time) {
t.Time = v
t.Valid = true
}
|
go
|
func (t *Time) SetValid(v time.Time) {
t.Time = v
t.Valid = true
}
|
[
"func",
"(",
"t",
"*",
"Time",
")",
"SetValid",
"(",
"v",
"time",
".",
"Time",
")",
"{",
"t",
".",
"Time",
"=",
"v",
"\n",
"t",
".",
"Valid",
"=",
"true",
"\n",
"}"
] |
// SetValid changes this Time's value and sets it to be non-null.
|
[
"SetValid",
"changes",
"this",
"Time",
"s",
"value",
"and",
"sets",
"it",
"to",
"be",
"non",
"-",
"null",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L132-L135
|
test
|
guregu/null
|
time.go
|
Ptr
|
func (t Time) Ptr() *time.Time {
if !t.Valid {
return nil
}
return &t.Time
}
|
go
|
func (t Time) Ptr() *time.Time {
if !t.Valid {
return nil
}
return &t.Time
}
|
[
"func",
"(",
"t",
"Time",
")",
"Ptr",
"(",
")",
"*",
"time",
".",
"Time",
"{",
"if",
"!",
"t",
".",
"Valid",
"{",
"return",
"nil",
"\n",
"}",
"\n",
"return",
"&",
"t",
".",
"Time",
"\n",
"}"
] |
// Ptr returns a pointer to this Time's value, or a nil pointer if this Time is null.
|
[
"Ptr",
"returns",
"a",
"pointer",
"to",
"this",
"Time",
"s",
"value",
"or",
"a",
"nil",
"pointer",
"if",
"this",
"Time",
"is",
"null",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/time.go#L138-L143
|
test
|
guregu/null
|
bool.go
|
NewBool
|
func NewBool(b bool, valid bool) Bool {
return Bool{
NullBool: sql.NullBool{
Bool: b,
Valid: valid,
},
}
}
|
go
|
func NewBool(b bool, valid bool) Bool {
return Bool{
NullBool: sql.NullBool{
Bool: b,
Valid: valid,
},
}
}
|
[
"func",
"NewBool",
"(",
"b",
"bool",
",",
"valid",
"bool",
")",
"Bool",
"{",
"return",
"Bool",
"{",
"NullBool",
":",
"sql",
".",
"NullBool",
"{",
"Bool",
":",
"b",
",",
"Valid",
":",
"valid",
",",
"}",
",",
"}",
"\n",
"}"
] |
// NewBool creates a new Bool
|
[
"NewBool",
"creates",
"a",
"new",
"Bool"
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L19-L26
|
test
|
guregu/null
|
bool.go
|
BoolFromPtr
|
func BoolFromPtr(b *bool) Bool {
if b == nil {
return NewBool(false, false)
}
return NewBool(*b, true)
}
|
go
|
func BoolFromPtr(b *bool) Bool {
if b == nil {
return NewBool(false, false)
}
return NewBool(*b, true)
}
|
[
"func",
"BoolFromPtr",
"(",
"b",
"*",
"bool",
")",
"Bool",
"{",
"if",
"b",
"==",
"nil",
"{",
"return",
"NewBool",
"(",
"false",
",",
"false",
")",
"\n",
"}",
"\n",
"return",
"NewBool",
"(",
"*",
"b",
",",
"true",
")",
"\n",
"}"
] |
// BoolFromPtr creates a new Bool that will be null if f is nil.
|
[
"BoolFromPtr",
"creates",
"a",
"new",
"Bool",
"that",
"will",
"be",
"null",
"if",
"f",
"is",
"nil",
"."
] |
80515d440932108546bcade467bb7d6968e812e2
|
https://github.com/guregu/null/blob/80515d440932108546bcade467bb7d6968e812e2/bool.go#L34-L39
|
test
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.