Golang で HTTP client 実装

Github から自分のリポジトリのリストを取得するサンプル。

ファイル構成

main.go
/app
  ├ /domain
  │   └ GithubRepositories.go
  │
  └ /infrastructure
      └ Http.go

サンプルコード

/app/infrastructure/Http.go

package infrastructure

import (
	"net/http"
	"net/url"
	"strings"
	"io/ioutil"
)

type Http struct {}

func NewHttp() *Http {
	return new(Http)
}

func (h *Http) GetResponse(request *http.Request) (response *http.Response, err error) {
	client := &http.Client{}
	response, err = client.Do(request)
	if err != nil {
		return nil, err
	}
	return response, nil
}

func (h *Http) GetBody(response *http.Response) (body string, err error) {
	b, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

func (h *Http) setParams(values url.Values, params map[string]string) url.Values {
	for key, param := range params {
		values.Add(key, param)
	}
	return values
}

func (h *Http) Get(URL string, params map[string]string) (request *http.Request, err error) {

	request, err = http.NewRequest("GET", URL, nil)

	if err != nil {
		return nil, err
	}

	request.URL.RawQuery = h.setParams(request.URL.Query(), params).Encode()
	return request, nil
}

func (h *Http) Post(URL string, params map[string]string) (request *http.Request, err error) {

	request, err = http.NewRequest("POST", URL, strings.NewReader(h.setParams(url.Values{}, params).Encode()))

	if err != nil {
		return nil, err
	}

	return request, nil
}

func (h *Http) Delete(URL string, params map[string]string) (request *http.Request, err error) {

	request, err = http.NewRequest("DELETE", URL, strings.NewReader(h.setParams(url.Values{}, params).Encode()))

	if err != nil {
		return nil, err
	}

	return request, nil
}

/app/domain/GithubRepositories.go

package domain

import (
	"time"
)

type GithubRepositories struct {
	ID int `json:"id"`
	Name string `json:"name"`
	CreatedAt time.Time `json:"created_at"`
}

type GithubRepositoriesForGet struct {
	ID int
	Name string
	CreatedAt time.Time
}

func (u *GithubRepositories) BuildForGet() GithubRepositoriesForGet {
	repos := GithubRepositoriesForGet{}
	repos.ID = u.ID
	repos.Name = u.Name
	repos.CreatedAt = u.CreatedAt
	return repos
}

使い方

main.go

package main

import (
	"fmt"

	"github.com/psychedelicnekopunch/gin-clean-architecture/app/domain"
	"github.com/psychedelicnekopunch/gin-clean-architecture/app/infrastructure"
)

func getList(params map[string]string) (repos []domain.GithubRepositories, err error) {
	http := infrastructure.NewHttp()
	
	request, err := http.Get("https://api.github.com/users/psychedelicnekopunch/repos", params)
	response, err := http.GetResponse(request)

	if err != nil {
		return []domain.GithubRepositories{}, err
	}

	body, err := http.GetBody(response)

	if err != nil {
		return []domain.GithubRepositories{}, err
	}

	dec := json.NewDecoder(strings.NewReader(body))
	dec.Decode(&repos)

	if len(repos) == 0 {
		return repos, errors.New("not found repos")
	}

	return repos, nil
}

func main() {

	params := map[string]string{}
	params["sort"] = "created"
	params["direction"] = "desc"

	repos, err := getList.GetRepositoryList(params)

	if err != nil {
		fmt.Print(err.Error())
		return
	}

	for _, repo := range repos {
		fmt.Print(repo.BuildForGet())
	}
}
カテゴリー:Go