Skip to content

Instantly share code, notes, and snippets.

@ziadoz ziadoz/gists.go
Created Jul 26, 2019

Embed
What would you like to do?
Test Golang API Client Using httptest Package
package gists
import (
"encoding/json"
"fmt"
"net/http"
)
type Api struct {
client *http.Client
headers map[string]string
BaseURL string
}
type Gist struct {
Id string `json:"id,omitempty"`
Url string `json:"url,omitempty"`
}
func NewApi() *Api {
return &Api{
client: &http.Client{},
headers: map[string]string{"Accept": "application/vnd.github.v3+json"},
BaseURL: "https://api.github.com",
}
}
func (api *Api) GetUserGists(username string) ([]Gist, error) {
request, err := http.NewRequest("GET", fmt.Sprintf("%s/users/%s/gists", api.BaseURL, username), nil)
if err != nil {
return []Gist{}, err
}
for k, v := range api.headers {
request.Header.Set(k, v)
}
response, err := api.client.Do(request)
if err != nil {
return []Gist{}, err
}
defer response.Body.Close()
gists := []Gist{}
err = json.NewDecoder(response.Body).Decode(&gists)
if err != nil {
return []Gist{}, err
}
return gists, nil
}
package gists
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestGetUserRepos(t *testing.T) {
id := "repo1"
url := "http://gists.github.com/repo1"
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte(`[{"id":"` + id + `","url":"` + url + `"}]`))
})
client := httptest.NewServer(handler)
api := NewApi()
api.BaseURL = client.URL
gists, _ := api.GetUserGists("foobar")
if len(gists) != 1 {
t.Error("returned more than one gist")
}
if gists[0].Id != id {
t.Errorf("gist.Id is not %s", id)
}
if gists[0].Url != url {
t.Errorf("gist.Url is not %s", url)
}
}
package main
import (
"fmt"
"log"
"github.com/ziadoz/gists/http-client-testing/pkg/gists"
)
func main() {
gists, err := gists.NewApi().GetUserGists("ziadoz")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%+v", gists)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.