Skip to content

Instantly share code, notes, and snippets.

@dimiro1
Created February 26, 2018 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimiro1/83a126c1bb8389fc7005a00ff6d2295a to your computer and use it in GitHub Desktop.
Save dimiro1/83a126c1bb8389fc7005a00ff6d2295a to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"math/rand"
"net/http"
"github.com/gin-gonic/gin/json"
)
type experiment struct {
controlFn func() error
candidateFn func() error
}
func (e *experiment) Control(fn func() error) {
e.controlFn = fn
}
func (e *experiment) Candidate(fn func() error) {
e.candidateFn = fn
}
func (e *experiment) Run() error {
// Validate functions
// Could execute many experiments
// 1. Split the calls
// 2. Execute the new function and compare the value, but ignore the response
if rand.Float64() < 0.5 {
e.controlFn()
} else {
e.candidateFn()
}
return nil
}
func main() {
for i := 0; i < 10; i++ {
fmt.Println(ip())
}
}
func ip() (string, error) {
e := experiment{}
var myip string
e.Control(func() error {
myip = "127.0.0.1"
return nil
})
e.Candidate(func() error {
resp, err := http.Get("https://api.ipify.org?format=json")
if err != nil {
return err
}
ipStruct := struct {
IP string `json:"ip"`
}{}
err = json.NewDecoder(resp.Body).Decode(&ipStruct)
if err != nil {
return err
}
myip = ipStruct.IP
return nil
})
err := e.Run()
if err != nil {
return myip, err
}
return myip, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment