Skip to content

Instantly share code, notes, and snippets.

@stefanooldeman
Last active August 29, 2015 14:17
Show Gist options
  • Save stefanooldeman/e61ff0236bfc4b0a78bd to your computer and use it in GitHub Desktop.
Save stefanooldeman/e61ff0236bfc4b0a78bd to your computer and use it in GitHub Desktop.
Go interfaces to play with
// this is based on a blog post from @relistan, http://relistan.com/writing-testable-apps-in-go/
package main
import (
"errors"
"fmt"
"strings"
)
type HttpResponseFetcher interface {
Fetch(url string) ([]byte, error)
}
var infoOutput []byte = []byte(`{ "Environment": "production" }`)
var statusOutput []byte = []byte(`{ "Status": "up" }`)
type stubFetcher struct{}
func (fetcher stubFetcher) Fetch(url string) ([]byte, error) {
if strings.Contains(url, "/info") {
return infoOutput, nil
}
if strings.Contains(url, "/status") {
return statusOutput, nil
}
return nil, errors.New("Don't recognize URL: " + url)
}
func main() {
var fetcher HttpResponseFetcher = stubFetcher{}
data, _ := fetcher.Fetch("/info")
fmt.Println("Hello, playground", data)
}
// my conclusion from this test is that types/structs don't implement any interface.
// Unless when a variable is assigned with var varname <T> that the interface is _used_.
package main
import "fmt"
type Store interface {
initSession(url string) error
Session() string
}
type MongoStore struct {
session string
}
func New() *MongoStore {
return &MongoStore{}
}
func (m *MongoStore) initSession(dbURI string) error {
m.session = dbURI
return nil
}
func (m *MongoStore) Session() string { return m.session }
func FindSomething(store Store) string {
// this was the goal, retreiving the session for an initialized store.
return store.Session()
}
func main() {
store := New()
store.initSession("url://foobar:180")
fmt.Println(FindSomething(store))
}
// This snippet is proof that real world cannot be demostrated by trivial examples (the Session() method defined in the interface is of type string, which is not true in the real world).
// The Session should be an attribute that i can read from MongoStore because it might be a datatype specific to the implementation.
// there must be more to learn and overcome this issue.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment