Skip to main content

Day26 建立簡易版imgur - (建立http client interface)

在這邊測試的部分,我主要不是希望要測試,而是希望可以透過這樣的開發流程,讓自己可以小幅度的開發需要的程式,再一步一步的將寫好的程式組合起來 而我們目前在pcloud這邊,第一步我想先寫我們要怎麼知道說access_token可以正常運作的內容

但目前如果要串接pcloud,我們需要有辦法去詢問pcloud的server,因此會先需要有個http的client的interface 而目前我們需要的功能有

  • Get
  • Post

並且還要能在其中設定header的token

如此,要先建立一個httpClient,然後先完成Get的function,並且他要能成功接收需要的資料 在這邊,我也先找了一個公開的api來進行開發用測試 https://jsonplaceholder.typicode.com/todos/1 這個api會固定回應

{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}

因此在這邊先寫上第一組測試來表示需要的內容

		It("Get", func() {
// !!!說明1!!!
var _client IHttpClient
resp, err := _client.Get("https://jsonplaceholder.typicode.com/todos/1")
Expect(err).ShouldNot(HaveOccurred())
f := new(struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
})
err = json.Unmarshal(resp.Body, f)
Expect(err).ShouldNot(HaveOccurred())
Expect(*f).Should(Equal(struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}{
UserId: 1,
Id: 1,
Title: "delectus aut autem",
Completed: false,
}))
})

說明一 在這邊沒有將_client實際實作出來,就僅有寫上預期想要的function,緊接著會發現提示說到有很多錯誤

  1. 要先建立一個IHttpClient的interface
type IHttpClient interface {  
Get(url string) (resp struct{ Body string }, err error)
}
  1. 當建立了這個Interface,這個測試應該就可以運行了,但他會出現
runtime error: invalid memory address or nil pointer dereference

原因為,我們並未真的實作IHttpClient,所以我們要建立一個真的HttpClient

type HttpClient struct {  
}
func (h *HttpClient) Get(url string) (resp Response, err error) {
return
}

並且在測試的程式中將IHttpClient放入

var _client IHttpClient = HttpClient{}

如此一來,就可以完成我們第一個紅燈的測試了 會得到以下回應

Unexpected error:
<*json.SyntaxError | 0xc0002100d8>: {
msg: "unexpected end of JSON input",
Offset: 0,
}
unexpected end of JSON input

client_test.go

package httpClient  

import (
"encoding/json"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

var _ = Describe("Client", func() {
When("Http Client", func() {
It("Get", func() {
var _client IHttpClient = &HttpClient{}
resp, err := _client.Get("https://jsonplaceholder.typicode.com/todos/1")
Expect(err).ShouldNot(HaveOccurred())
f := new(struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
})
err = json.Unmarshal(resp.Body, f)
Expect(err).ShouldNot(HaveOccurred())
Expect(*f).Should(Equal(struct {
UserId int `json:"userId"`
Id int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}{
UserId: 1,
Id: 1,
Title: "delectus aut autem",
Completed: false,
}))
})
})
})

client.go

package httpClient  

type Response struct {
Body []byte
}

type IHttpClient interface {
Get(url string) (resp Response, err error)
}

type HttpClient struct {
}

func (h *HttpClient) Get(url string) (resp Response, err error) {
return
}