-
Notifications
You must be signed in to change notification settings - Fork 0
/
Client.go
65 lines (52 loc) · 1.95 KB
/
Client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package score
import (
"errors"
"fmt"
scoreApi "github.com/kneu-messenger-pigeon/score-api"
"net/http"
"strconv"
)
const Version = "/v1"
type ClientInterface interface {
GetStudentDisciplines(studentId uint32) (response scoreApi.DisciplineScoreResults, err error)
GetStudentDiscipline(studentId uint32, disciplineId int) (response scoreApi.DisciplineScoreResult, err error)
GetStudentScore(studentId uint32, disciplineId int, lessonId int) (response scoreApi.DisciplineScore, err error)
}
type Client struct {
Host string
}
func (client *Client) GetStudentDisciplines(studentId uint32) (response scoreApi.DisciplineScoreResults, err error) {
err = client.doRequest(fmt.Sprintf("/students/%d/disciplines", studentId), &response)
return
}
func (client *Client) GetStudentDiscipline(studentId uint32, disciplineId int) (response scoreApi.DisciplineScoreResult, err error) {
err = client.doRequest(fmt.Sprintf("/students/%d/disciplines/%d", studentId, disciplineId), &response)
return
}
func (client *Client) GetStudentScore(studentId uint32, disciplineId int, lessonId int) (response scoreApi.DisciplineScore, err error) {
err = client.doRequest(
fmt.Sprintf("/students/%d/disciplines/%d/scores/%d", studentId, disciplineId, lessonId),
&response,
)
return
}
func (client *Client) doRequest(requestUri string, responseInterface any) error {
var response *http.Response
request, err := http.NewRequest(http.MethodGet, client.Host+Version+requestUri, nil)
if err == nil {
response, err = http.DefaultClient.Do(request)
if err == nil && response.StatusCode != 200 {
errorResponse := scoreApi.ErrorResponse{}
err = unmarshalResponse(response, &errorResponse)
if err == nil && errorResponse.Error != "" {
err = errors.New("API error: " + errorResponse.Error)
} else {
err = errors.New("Receive http code: " + strconv.Itoa(response.StatusCode))
}
}
}
if err == nil {
err = unmarshalResponse(response, &responseInterface)
}
return err
}