features/bootstrapping #1

Merged
jtom38 merged 24 commits from features/bootstrapping into main 2024-06-02 19:55:25 -07:00
4 changed files with 97 additions and 1 deletions
Showing only changes of commit 75160e0704 - Show all commits

16
apiclient/client.go Normal file
View File

@ -0,0 +1,16 @@
package apiclient
const (
HeaderContentType = "Content-Type"
MIMEApplicationForm = "application/x-www-form-urlencoded"
)
type ApiClient struct {
Users Users
}
func New(serverAddress string) ApiClient {
return ApiClient{
Users: newUserService(serverAddress),
}
}

47
apiclient/users.go Normal file
View File

@ -0,0 +1,47 @@
package apiclient
import (
"fmt"
"net/http"
"net/url"
"git.jamestombleson.com/jtom38/newsbot-api/domain"
)
const (
UserLoginRoute = "api/v1/users/login"
UserRegisterRoute = "api/v1/users/register"
)
type Users interface {
Login(username, password string) (domain.LoginResponse, error)
}
type userClient struct {
serverAddress string
client http.Client
}
func newUserService(serverAddress string) userClient {
return userClient{
serverAddress: serverAddress,
client: http.Client{},
}
}
func (a userClient) Login(username, password string) (domain.LoginResponse, error) {
endpoint := fmt.Sprintf("%s/%s", a.serverAddress, UserLoginRoute)
param := url.Values{}
param.Set("username", username)
param.Set("password", password)
// Create the struct we are expecting back from the API so we can have it populated
var bind = domain.LoginResponse{}
err := PostUrlForm(a.client, endpoint, param, &bind)
if err != nil {
return domain.LoginResponse{}, err
}
return bind, nil
}

31
apiclient/util.go Normal file
View File

@ -0,0 +1,31 @@
package apiclient
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
func PostUrlForm(client http.Client, endpoint string, param url.Values, t any) error {
payload := bytes.NewBufferString(param.Encode())
req, err := http.NewRequest(http.MethodPost, endpoint, payload)
if err != nil {
return err
}
req.Header.Set(HeaderContentType, MIMEApplicationForm)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&t)
if err != nil {
return err
}
return nil
}

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"git.jamestombleson.com/jtom38/newsbot-portal/apiclient"
"git.jamestombleson.com/jtom38/newsbot-portal/internal/config"
"git.jamestombleson.com/jtom38/newsbot-portal/internal/handlers"
)
@ -12,7 +13,8 @@ func main() {
ctx := context.Background()
cfg := config.New()
server := handlers.NewServer(ctx, cfg)
apiClient := apiclient.New(cfg.ServerAddress)
server := handlers.NewServer(ctx, cfg, apiClient)
fmt.Println("The server is online and waiting for requests.")
fmt.Printf("http://%v:8082\r\n", cfg.ServerAddress)