Skip to content

Instantly share code, notes, and snippets.

@zeddee
Created December 21, 2018 15:05
Show Gist options
  • Save zeddee/27cf8c6d8aafe3c22132c44d51b012e6 to your computer and use it in GitHub Desktop.
Save zeddee/27cf8c6d8aafe3c22132c44d51b012e6 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"time"
)
func getTypeOfError(err *url.Error) string {
if err.Timeout() {
return "Request timed out"
}
return "Unknown error"
}
func makeGetRequestToStatusAPI(urlToGet string) (string, error) {
req, err := http.NewRequest("GET", urlToGet, nil)
if err != nil {
return "", err
}
req.Header.Set("Accept", "application/json")
// Set timeout for request with context.Context
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
req.WithContext(ctx)
res, err := http.DefaultClient.Do(req)
if err != nil {
urlErr := err.(*url.Error)
return "", fmt.Errorf("%s when connecting to URL %s: %s", getTypeOfError(urlErr), urlErr.URL, err)
}
defer res.Body.Close()
if res.StatusCode/100 == 4 || res.StatusCode/100 == 5 {
return "", fmt.Errorf("Connecting to %s returned with status: %d", urlToGet, res.StatusCode)
}
var resBody string
if err := json.NewDecoder(res.Body).Decode(&resBody); err != nil {
return "", err
}
return resBody, nil
}
func main() {
url := "http://httpstat.us/200"
output, err := makeGetRequestToStatusAPI(url)
if err != nil {
log.Fatal(err)
}
fmt.Println("Output:", output)
}
package main
import (
"testing"
)
func Test_makeGetRequestToStatusAPI(t *testing.T) {
type args struct {
urlToGet string
}
tests := []struct {
name string
args args
want string
wantErr bool
}{
{"HTTP:200", args{"http://httpstat.us/200"}, "200 OK", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := makeGetRequestToStatusAPI(tt.args.urlToGet)
if (err != nil) != tt.wantErr {
t.Errorf("makeGetRequestToStatusAPI() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("makeGetRequestToStatusAPI() = %v, want %v", got, tt.want)
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment