Cleaning up examples in main and splitting the code into suitable packages

This commit is contained in:
Imbus 2024-03-02 02:38:26 +01:00
parent 5cefed405f
commit 469f866554
5 changed files with 120 additions and 29 deletions

View file

@ -0,0 +1,23 @@
package types
// User struct represents a user in the system
type User struct {
UserId string `json:"userId"`
Username string `json:"username"`
Password string `json:"password"`
}
// If the user needs to be served over the api, we dont want to send the password
// ToPublicUser converts a User to a PublicUser
func (u *User) ToPublicUser() (*PublicUser, error) {
return &PublicUser{
UserId: u.UserId,
Username: u.Username,
}, nil
}
// PublicUser represents a user that is safe to send over the API (no password)
type PublicUser struct {
UserId string `json:"userId"`
Username string `json:"username"`
}

View file

@ -0,0 +1,35 @@
package types
import "testing"
// NewUser returns a new User
func TestNewUser(t *testing.T) {
u := User{
UserId: "123",
Username: "test",
Password: "password",
}
if u.UserId != "123" {
t.Errorf("Expected user id to be 123, got %s", u.UserId)
}
if u.Username != "test" {
t.Errorf("Expected username to be test, got %s", u.Username)
}
if u.Password != "password" {
t.Errorf("Expected password to be password, got %s", u.Password)
}
}
func TestToPublicUser(t *testing.T) {
u := User{
UserId: "123",
Username: "test",
Password: "password",
}
_, err := u.ToPublicUser()
if err != nil {
t.Errorf("Expected no error, got %s", err)
}
}