Compare commits

..

1 Commits

Author SHA1 Message Date
50dda77019 go.mod update priv git url 2024-05-30 17:01:18 +02:00
9 changed files with 277 additions and 22 deletions

View File

@@ -3,8 +3,7 @@ package api
import (
"fmt"
"git.ego.freeddns.org/egommerce/api-entities/basket"
basket "git.ego.freeddns.org/egommerce/api-entities/basket/dto"
def "git.pbiernat.dev/egommerce/api-entities/http"
"github.com/go-redis/redis/v8"
)
@@ -16,9 +15,9 @@ type BasketAPI struct {
httpClient *HttpClient
}
func (a *BasketAPI) GetBasket(basketID string) (*basket.GetBasketResponseDTO, error) {
req := &basket.GetBasketRequestDTO{BasketID: basketID}
res := new(basket.GetBasketResponse)
func (a *BasketAPI) GetBasket(basketID string) (*def.GetBasketResponse, error) {
req := &def.GetBasketRequest{BasketID: basketID}
res := new(def.GetBasketResponse)
if err := a.httpClient.SendGet("basket-svc", "/api/v1/basket", req, res); err != nil {
return nil, err
}
@@ -26,9 +25,9 @@ func (a *BasketAPI) GetBasket(basketID string) (*basket.GetBasketResponseDTO, er
return res, nil
}
func (a *BasketAPI) GetBasketItems(basketID string) ([]*basket.GetBasketItemsResponseDTO, error) {
func (a *BasketAPI) GetBasketItems(basketID string) ([]*def.GetBasketItemsResponse, error) {
url := fmt.Sprintf("/api/v1/basket/%s/items", basketID)
var res []*basket.GetBasketItemsResponseDTO
var res []*def.GetBasketItemsResponse
if err := a.httpClient.SendGet("basket-svc", url, nil, &res); err != nil {
return nil, err
}

View File

@@ -3,7 +3,7 @@ package api
import (
"fmt"
def "git.pbiernat.io/egommerce/api-entities/http"
def "git.pbiernat.dev/egommerce/api-entities/http"
"github.com/go-redis/redis/v8"
)

200
consul/discovery.go Normal file
View File

@@ -0,0 +1,200 @@
package consul
import (
"fmt"
"net/http"
"strconv"
"time"
"git.pbiernat.dev/egommerce/go-api-pkg/config"
consul "github.com/hashicorp/consul/api"
"github.com/hashicorp/consul/connect"
)
type Service struct {
Name string
Address string
appID string
domain string
pathPrefix string
port int
ttl time.Duration
client *consul.Client
agent *consul.Agent
connect *connect.Service
kv *consul.KV
}
var ErrServiceUnavailable = fmt.Errorf("Service is unavailable")
func NewService(servAddr, id, name, hostname, domain, pathPrefix string, appPort int) (*Service, error) {
s := new(Service)
s.Name = name
s.Address = hostname
s.appID = id
s.domain = domain
s.pathPrefix = pathPrefix
s.port = appPort
s.ttl = time.Second * 10
client, err := consul.NewClient(newClientConfig(servAddr))
if err != nil {
return nil, err
}
s.client = client
s.agent = client.Agent()
s.kv = client.KV()
return s, nil
}
func newClientConfig(serverAddr string) *consul.Config {
conf := consul.DefaultConfig()
conf.Address = serverAddr
return conf
}
func (s *Service) GetID() string {
return fmt.Sprintf("%s:%s", s.Name, s.appID)
}
func (s *Service) GetFullAddr() string {
isTLS := s.port == 443
proto := "http"
if isTLS {
proto = "https"
}
return fmt.Sprintf("%s://%s:%d/", proto, s.domain, s.port)
}
func (s *Service) Register() error {
def := &consul.AgentServiceRegistration{
ID: s.GetID(),
// Kind: consul.ServiceKindConnectProxy,
Name: s.Name,
Address: s.Address,
Port: s.port,
Tags: s.getTags(),
// Connect: &consul.AgentServiceConnect{Native: true},
// Proxy: &consul.AgentServiceConnectProxyConfig{
// DestinationServiceName: s.Name,
// },
Check: &consul.AgentServiceCheck{
TTL: s.ttl.String(),
Status: "passing",
DeregisterCriticalServiceAfter: "10s",
},
}
if err := s.agent.ServiceRegister(def); err != nil {
return err
}
return nil
}
func (s *Service) Unregister() error {
return s.agent.ServiceDeregister(s.GetID())
}
func (s *Service) RegisterHealthChecks() {
go func() { // startup register
ticker := time.NewTicker(time.Second * 1)
for range ticker.C {
if ok, _ := s.healthCheck(); ok {
ticker.Stop()
}
}
}()
go func() { // TTL
interval := s.ttl - (time.Second * 2) // 2 seconds overhead
ticker := time.NewTicker(interval)
for range ticker.C {
if _, err := s.healthCheck(); err != nil {
fmt.Printf("TTL Error #: %v\n", err)
}
}
}()
}
func (s *Service) Connect() (*connect.Service, error) {
// l := hclog.New(&hclog.LoggerOptions{
// Name: "consul-registry",
// Level: hclog.Trace,
// })
svc, err := connect.NewService(s.Name, s.client)
s.connect = svc
cnf := svc.ServerTLSConfig()
fmt.Printf("CONNECT SERVER:: %s CONFIG:: %v\n", s.Name, cnf)
for k, c := range cnf.Certificates {
fmt.Printf("CONNECT CERT %d: %v", k, c)
}
return svc, err
}
func (s *Service) KV() *consul.KV {
return s.kv
}
func (s *Service) healthCheck() (bool, error) {
alive := func() bool {
client := &http.Client{}
healthUrl := fmt.Sprintf("%s%s?name=%s", s.GetFullAddr(), "health", s.Name)
req, err := http.NewRequest(http.MethodGet, healthUrl, nil)
if err != nil {
return false
}
req.Header.Set("User-Agent", "service/internal")
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
var body []byte
resp.Body.Read(body)
return resp.StatusCode == http.StatusOK
}()
if alive {
if err := s.agent.PassTTL("service:"+s.GetID(), "OK"); err != nil {
fmt.Printf("Failed to pass TTL: %v", err)
return false, err
}
return true, nil
}
if err := s.agent.FailTTL("service:"+s.GetID(), ErrServiceUnavailable.Error()); err != nil {
return false, err
}
return false, ErrServiceUnavailable
}
func (s *Service) getTags() []string {
tags := []string{
"traefik.enable=true",
"traefik.http.routers." + s.Name + ".rule=PathPrefix(`" + s.pathPrefix + "`)",
"traefik.http.routers." + s.Name + ".entryPoints=https",
// "traefik.http.routers." + s.Name + ".tls=true",
"traefik.http.routers." + s.Name + ".service=" + s.Name,
"traefik.http.routers." + s.Name + ".middlewares=auth_" + s.Name + ",requestid_" + s.Name + ",stripprefix_" + s.Name,
"traefik.http.services." + s.Name + ".loadbalancer.server.scheme=http",
"traefik.http.services." + s.Name + ".loadbalancer.server.port=" + strconv.Itoa(s.port),
"traefik.http.services." + s.Name + ".loadbalancer.passhostheader=false",
"traefik.http.middlewares.auth_" + s.Name + ".plugin.auth.handlerURL=" + config.GetEnv("AUTH_HANDLER_URL", ""),
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authRequestHeaders=Cookie",
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.authResponseHeaders=Set-Cookie, Server",
// "traefik.http.middlewares.auth_" + s.Name + ".forwardauth.trustForwardHeader=true",
"traefik.http.middlewares.requestid_" + s.Name + ".plugin.requestid.headerName=X-Request-ID",
"traefik.http.middlewares.stripprefix_" + s.Name + ".stripprefix.prefixes=" + s.pathPrefix,
"traefik.tls.certificates.certfile=/certs/client.cert",
"traefik.tls.certificates.keyfile=/certs/client.key",
}
return tags
}

17
fluentd/config.go Normal file
View File

@@ -0,0 +1,17 @@
package fluentd
import (
"strconv"
"strings"
)
func ParseAddr(addr string) (string, int, error) {
p := strings.Split(addr, ":")
fHost := p[0]
fPort, err := strconv.Atoi(p[1])
if err != nil {
return "", 0, err
}
return fHost, fPort, nil
}

41
fluentd/logger.go Normal file
View File

@@ -0,0 +1,41 @@
package fluentd
import (
"fmt"
"log"
"github.com/fluent/fluent-logger-golang/fluent"
)
type Logger struct {
fluent *fluent.Fluent
appName string
}
func NewLogger(appName, fHost string, fPort int) (*Logger, error) {
config := fluent.Config{
FluentHost: fHost,
FluentPort: fPort,
// WriteTimeout: -1,
}
fluent, err := fluent.New(config)
if err != nil {
return nil, err
}
return &Logger{fluent, appName}, nil
}
func (l *Logger) Log(format string, v ...any) {
mapData := map[string]string{
"message": fmt.Sprintf(format, v...),
}
err := l.fluent.Post(l.appName, mapData)
if err != nil {
log.Println("Error sending log: ", err)
}
}
func (l *Logger) Close() error {
return l.fluent.Close()
}

8
go.mod
View File

@@ -1,17 +1,18 @@
module git.ego.freeddns.org/egommerce/go-api-pkg
module git.pbiernat.io/egommerce/go-api-pkg
go 1.24
go 1.18
require (
git.pbiernat.io/egommerce/api-entities v0.0.26
github.com/fluent/fluent-logger-golang v1.9.0
github.com/go-redis/redis/v8 v8.11.5
github.com/hashicorp/consul v1.16.0
github.com/hashicorp/consul/api v1.22.0
github.com/joho/godotenv v1.5.1
github.com/streadway/amqp v1.0.0
)
require (
git.ego.freeddns.org/egommerce/api-entities v0.3.0 // indirect
github.com/DataDog/datadog-go v3.2.0+incompatible // indirect
github.com/armon/go-metrics v0.4.1 // indirect
github.com/armon/go-radix v1.0.0 // indirect
@@ -70,7 +71,6 @@ require (
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.37.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/rabbitmq/amqp091-go v1.10.0 // indirect
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529 // indirect
github.com/stretchr/objx v0.5.0 // indirect
github.com/stretchr/testify v1.8.3 // indirect

10
go.sum
View File

@@ -35,10 +35,8 @@ cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohl
cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs=
cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
git.ego.freeddns.org/egommerce/api-entities v0.2.5 h1:A7KQNXLB3l0ck7/R6MzyU33H490feZOlEodnU6bC+DA=
git.ego.freeddns.org/egommerce/api-entities v0.2.5/go.mod h1:xr9mW9DKq+oNO4cMqtqY3VCAVCn6iImw4MqNj51dTFc=
git.ego.freeddns.org/egommerce/api-entities v0.3.0 h1:IhJNOfze8/D8Hgy8Mr9hoFEwrg45xeFSnVRUnUrC5xc=
git.ego.freeddns.org/egommerce/api-entities v0.3.0/go.mod h1:IqynARw+06GOm4eZGZuepmbi7bUxWBnOB4jd5cI7jf8=
git.pbiernat.dev/egommerce/api-entities v0.0.26 h1:Avz02GINwuYWOjw1fmZIJ3QgGEIz3a5vRQZNaxxUQIk=
git.pbiernat.dev/egommerce/api-entities v0.0.26/go.mod h1:+BXvUcr6Cr6QNpJsW8BUfe1vVILdWDADNE0e3u0lNvU=
github.com/Azure/azure-sdk-for-go v44.0.0+incompatible h1:e82Yv2HNpS0kuyeCrV29OPKvEiqfs2/uJHic3/3iKdg=
github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs=
github.com/Azure/go-autorest/autorest v0.11.18 h1:90Y4srNYrwOtAgVo3ndrQkTYn6kf1Eg/AjTFJ8Is2aM=
@@ -472,8 +470,6 @@ github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1
github.com/prometheus/procfs v0.7.3/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
github.com/prometheus/procfs v0.8.0 h1:ODq8ZFEaYeCaZOJlZZdJA2AbQR98dSHSM1KW/You5mo=
github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0uaxHdg830/4=
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
github.com/renier/xmlrpc v0.0.0-20170708154548-ce4a1a486c03 h1:Wdi9nwnhFNAlseAOekn6B5G/+GMtks9UKbvRU/CMM/o=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
@@ -491,6 +487,8 @@ github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
github.com/softlayer/softlayer-go v0.0.0-20180806151055-260589d94c7d h1:bVQRCxQvfjNUeRqaY/uT0tFuvuFY0ulgnczuR684Xic=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/streadway/amqp v1.0.0 h1:kuuDrUJFZL1QYL9hUNuCxNObNzB0bV/ZG5jV3RWAQgo=
github.com/streadway/amqp v1.0.0/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=

View File

@@ -3,7 +3,7 @@ package rabbitmq
import (
"log"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/streadway/amqp"
)
func Open(url string) (*amqp.Connection, *amqp.Channel, error) {

View File

@@ -6,12 +6,12 @@ import (
"fmt"
"log"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/streadway/amqp"
)
type Message map[string]interface{}
func Serialize(msg any) (string, error) { // FIXME move to separate service
func Serialize(msg any) (string, error) {
var b bytes.Buffer
encoder := json.NewEncoder(&b)
err := encoder.Encode(msg)
@@ -19,7 +19,7 @@ func Serialize(msg any) (string, error) { // FIXME move to separate service
return b.String(), err
}
func Deserialize(b []byte) (Message, error) { // FIXME move to separate service
func Deserialize(b []byte) (Message, error) {
var msg Message
buf := bytes.NewBuffer(b)
decoder := json.NewDecoder(buf)