Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions .idea/doccer.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ import (
"context"
"doccer/data"
"doccer/model"
"doccer/prom"
"encoding/json"
mux "github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
)

const (
accountIdContextKey = "account_id"
)

type Api struct {
useCases model.UseCasesInterface
}
Expand All @@ -20,6 +26,10 @@ func NewApi(x model.UseCasesInterface) *Api {

func (a *Api) Router() http.Handler {
router := mux.NewRouter()

router.Use(prom.Measurer())
router.Use(a.logger)

router.HandleFunc("/register", a.register).Methods(http.MethodPost)
router.HandleFunc("/login", a.login).Methods(http.MethodPost)
router.HandleFunc("/logout", a.auth(a.logout, true)).Methods(http.MethodPost)
Expand All @@ -46,6 +56,8 @@ func (a *Api) Router() http.Handler {
router.HandleFunc("/users/groups/{group_id}/members", a.auth(a.removeMember, true)).Methods(http.MethodDelete)
router.HandleFunc("/users/groups/{group_id}/members", a.auth(a.addMember, true)).Methods(http.MethodPut)

router.Handle("/metrics", promhttp.Handler())

return router
}

Expand Down
60 changes: 60 additions & 0 deletions api/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package api

import (
"context"
"fmt"
"net/http"
"strings"
"time"
)

func (a *Api) authenticate(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
bearHeader := r.Header.Get("Authorization")
strArr := strings.Split(bearHeader, " ")
if len(strArr) != 2 {
w.WriteHeader(http.StatusBadRequest)
return
}
token := strArr[1]
id, err := a.useCases.Auth(token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), accountIdContextKey, id)
handler(w, r.WithContext(ctx))
}
}

type responseWriterObserver struct {
http.ResponseWriter
status int
wroteHeader bool
}

func (o *responseWriterObserver) WriteHeader(code int) {
o.ResponseWriter.WriteHeader(code)
if o.wroteHeader {
return
}
o.wroteHeader = true
o.status = code
}

func (o *responseWriterObserver) StatusCode() int {
if !o.wroteHeader {
return http.StatusOK
}
return o.status
}

func (a *Api) logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
o := &responseWriterObserver{ResponseWriter: w}
next.ServeHTTP(o, r)
fmt.Printf("method: %s; url: %s; status-code: %d; remote-addr: %s; duration: %v;\n",
r.Method, r.URL.String(), o.StatusCode(), r.RemoteAddr, time.Since(start))
})
}
110 changes: 110 additions & 0 deletions cmd/load-generator/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package main

import (
"github.com/brianvoe/gofakeit/v6"

"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"sync"
"time"
)

var config = struct {
address string
concurrencyLevel int
}{}

func init() {
address := flag.String("address", "http://localhost:8080", "doccer address")
concurrencyLevel := flag.Int("concurrency", 40, "a number of concurrent requests")
flag.Parse()

config.address = *address
config.concurrencyLevel = *concurrencyLevel
}

func main() {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan os.Signal, 1)
signal.Notify(ch, os.Interrupt)
defer func() {
signal.Stop(ch)
cancel()
}()

go func() {
select {
case <-ch:
cancel()
case <-ctx.Done():
}
}()

c := client{
c: http.Client{
Timeout: 10 * time.Second,
},
}

var wg sync.WaitGroup
wg.Add(config.concurrencyLevel)
for i := 0; i < config.concurrencyLevel; i++ {
go func(i int) {
err := worker(ctx, c)
fmt.Printf("worker %d finished, err: %v\n", i, err)
wg.Done()
}(i)
}
wg.Wait()
fmt.Println("all workers have been finished")
}

func worker(ctx context.Context, c client) error {
for {
select {
default:
_, err := c.createAccount(ctx, gofakeit.Username() + gofakeit.DigitN(9), gofakeit.Password(true, true, true, false, false, 16))
if err != nil {
fmt.Println("request failed:", err)
}
case <-ctx.Done():
fmt.Println("leaving worker")
return ctx.Err()
}
}
}

type client struct {
c http.Client
}

func (c client) createAccount(ctx context.Context, login, password string) (string, error) {
body := struct {
Login string `json:"login"`
Password string `json:"password"`
}{login, password}
s, err := json.Marshal(body)
if err != nil {
panic(err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, config.address+"/register", bytes.NewReader(s))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.c.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
return "", fmt.Errorf("failed to create account: %v", resp.Status)
}
return resp.Header.Get("Location"), nil
}
9 changes: 8 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,11 @@ services:
environment:
POSTGRES_PASSWORD: qwerty
volumes:
- ./initdb.sql:/docker-entrypoint-initdb.d/initdb.sql
- ./initdb.sql:/docker-entrypoint-initdb.d/initdb.sql

prometheus:
image: prom/prometheus
ports:
- 9090:9090
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ module doccer
go 1.16

require (
github.com/brianvoe/gofakeit/v6 v6.4.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gorilla/mux v1.8.0
github.com/prometheus/client_golang v1.10.0
github.com/lib/pq v1.10.2
golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2
)
Loading