Commit 51220f87 authored by Boris Mühmer's avatar Boris Mühmer
Browse files

added setviafunc example

parent 4fd69ed9
Loading
Loading
Loading
Loading
+61 −0
Original line number Diff line number Diff line
package setviafunc

import "fmt"

type Setviafunc struct {
}

func New() Setviafunc {
	return Setviafunc{}
}

func (s Setviafunc) String() string {
	return "<<Type is Setviafunc>>"
}

type Service struct {
	options map[string]interface{}
}

func NewService(of ...Setter) (*Service, error) {
	svc := &Service{
		options: map[string]interface{}{},
	}

	for _, s := range of {
		if err := s.Do(svc); err != nil {
			return nil, err
		}
	}

	return svc, nil
}

func (svc *Service) Run() error {
	return nil
}

type Setter interface {
	Do(*Service) error
}

type WithAddrPort struct {
	addr    string
	port    int
	addPort string
}

func NewAddrPort(addr string, port int) *WithAddrPort {
	return &WithAddrPort{
		addr:    addr,
		port:    port,
		addPort: fmt.Sprintf("%s:%d", addr, port),
	}
}

func (s *WithAddrPort) Do(svc *Service) error {
	svc.options["addr"] = s.addr
	svc.options["port"] = s.port
	svc.options["addrPort"] = s.addPort
	return nil
}
+17 −0
Original line number Diff line number Diff line
package setviafunc

import "testing"

func TestServiceSettings(t *testing.T) {
	svc, err := NewService(
		NewAddrPort("127.0.0.1", 2000),
	)

	if err != nil {
		t.Fatalf("NewService() failed with: %s", err)
	}

	if err := svc.Run(); err != nil {
		t.Fatalf("svc.Run() failed with: %s", err)
	}
}