Skip to content

Instantly share code, notes, and snippets.

@xrd
Last active August 29, 2015 14:02
Show Gist options
  • Save xrd/239b4f84c1196ba967a2 to your computer and use it in GitHub Desktop.
Save xrd/239b4f84c1196ba967a2 to your computer and use it in GitHub Desktop.
Testing HTTP Clients with Go
package main
import (
"io/ioutil"
"log"
"net/http"
)
type RealWebClient struct {
}
type WebClient interface {
Get(string) []byte
}
type Client struct {
Http WebClient
}
func (r *RealWebClient) Get(url string) []byte {
var body []byte
// Raw link: https://registry.hub.docker.com/u/bfirsh/ffmpeg/dockerfile/raw
client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
if resp, err := client.Do(req); nil != err {
log.Fatal(err)
} else {
defer resp.Body.Close()
body, _ = ioutil.ReadAll(resp.Body)
}
return body
}
package main
import (
"fmt"
"strings"
"testing"
)
type MockWebClient struct {
}
func getTestClient() *Client {
c := new(Client)
c.Http = new(MockWebClient)
return c
}
var jsonSample = ` { "fake" : "data" } `
func TestFullCircle(t *testing.T) {
c := getTestClient()
result := c.Http.Get("http://google.com")
if -1 != strings.Index(string(result), "fake") {
fmt.Println("We got our fake JSON data")
}
}
func (mwc *MockWebClient) Get(url string) []byte {
var rv []byte
if -1 != strings.Index(url, "google.com") {
// Return the JSON
rv = []byte(jsonSample)
}
return rv
}
package main
import "fmt"
func main() {
c := new(Client)
c.Http = new(RealWebClient)
body := c.Http.Get("http://google.com")
fmt.Println("Result\n\n" + string(body))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment