initial commit

This commit is contained in:
Karli
2025-09-18 18:36:15 +03:00
commit 8744935ee8
5 changed files with 94 additions and 0 deletions

3
greetings/go.mod Normal file
View File

@@ -0,0 +1,3 @@
module example.com/greetings
go 1.24.2

37
greetings/greetings.go Normal file
View File

@@ -0,0 +1,37 @@
package greetings
import (
"errors"
"fmt"
"math/rand"
)
func Hello(name string) (string, error) {
if name == "" {
return name, errors.New("empty name")
}
message := fmt.Sprintf(randomFormat(), name)
return message, nil
}
func Hellos(names []string) (map[string]string, error) {
messages := make(map[string]string)
for _, name := range names {
message, err := Hello(name)
if err != nil {
return nil, err
}
messages[name] = message
}
return messages, nil
}
func randomFormat() string {
formats := []string{
"Hi, %v. Welcome!",
"Great to see you, %v!",
"Hail, %v! Well met!",
}
return formats[rand.Intn(len(formats))]
}

View File

@@ -0,0 +1,26 @@
package greetings
import (
"regexp"
"testing"
)
// TestHelloName calls greetings.Hello with a name, checking
// for a valid return value.
func TestHelloName(t *testing.T) {
name := "Gladys"
want := regexp.MustCompile(`\b` + name + `\b`)
msg, err := Hello("Gladys")
if !want.MatchString(msg) || err != nil {
t.Errorf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)
}
}
// TestHelloEmpty calls greetings.Hello with an empty string,
// checking for an error.
func TestHelloEmpty(t *testing.T) {
msg, err := Hello("")
if msg != "" || err == nil {
t.Errorf(`Hello("") = %q, %v, want "", error`, msg, err)
}
}

7
hello/go.mod Normal file
View File

@@ -0,0 +1,7 @@
module example.com/hello
go 1.24.2
replace example.com/greetings => ../greetings
require example.com/greetings v0.0.0-00010101000000-000000000000

21
hello/hello.go Normal file
View File

@@ -0,0 +1,21 @@
package main
import (
"fmt"
"log"
"example.com/greetings"
)
func main() {
log.SetPrefix("greetings: ")
log.SetFlags(0)
names := []string{"Gladys", "Samantha", "Darrin"}
messages, err := greetings.Hellos(names)
if err != nil {
log.Fatal(err)
}
fmt.Println(messages)
}