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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
.idea
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module second-task

go 1.22.6
34 changes: 34 additions & 0 deletions task2/cmd/client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package main

import (
"fmt"
"net/http"
clientRequest "second-task/task2/internal/client"
"time"
)

func main() {
client := http.Client{
Timeout: 100 * time.Second,
}
version, err := clientRequest.RequestVersion(&client)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(version)

outputString, err := clientRequest.DecodeRequest(&client)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(outputString)

result, statusCode, err := clientRequest.HardOpRequest(&client)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(result, statusCode)
}
28 changes: 28 additions & 0 deletions task2/cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package main

import (
"fmt"
"net/http"
handlers "second-task/task2/internal/server"
"time"
)

func main() {
PORT := ":8001"
mux := http.NewServeMux()
server := &http.Server{
Addr: PORT,
Handler: mux,
IdleTimeout: 100 * time.Second,
ReadTimeout: 0 * time.Second,
WriteTimeout: 0 * time.Second,
}
mux.Handle("/version", http.HandlerFunc(handlers.GetVersion))
mux.Handle("/decode", http.HandlerFunc(handlers.Decode))
mux.Handle("/hard-op", http.HandlerFunc(handlers.HardOp))
err := server.ListenAndServe()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отсутствует gracefull shutdown. Хорошо бы его добавить.

if err != nil {
fmt.Println("Ошибка при запуске сервера")
return
}
}
62 changes: 62 additions & 0 deletions task2/internal/client/requests.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package client

import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
"second-task/task2/internal/server"
"time"
)

func RequestVersion(client *http.Client) (string, error) {
request, err := http.NewRequest(http.MethodGet, "http://localhost:8001/version", nil)
if err != nil {
return "", errors.New("ошибка при создании запроса")
}
httpData, err := client.Do(request)
if err != nil {
return "", errors.New("ошибка при отправке запроса")
}

return httpData.Header.Get("Version"), nil
}

func DecodeRequest(client *http.Client) (string, error) {
input := server.InputJson{
InputString: "YWJjMTIzIT8kKiYoKSctPUB+",
}
jsonData, _ := json.Marshal(input)
request, err := http.NewRequest(http.MethodPost, "http://localhost:8001/decode", bytes.NewBuffer(jsonData))
if err != nil {
return "", errors.New("ошибка при создании запроса")
}
httpData, err := client.Do(request)
if err != nil {
return "", errors.New("ошибка при отправке запроса")
}
var output server.OutputJson
data, _ := io.ReadAll(httpData.Body)
_ = json.Unmarshal(data, &output)
return output.OutputString, nil
}

func HardOpRequest(client *http.Client) (bool, int, error) {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
requestWithTimeout, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://localhost:8001/hard-op", nil)
if err != nil {
return false, 0, errors.New("ошибка при создании запроса")
}
httpData, err := client.Do(requestWithTimeout)
if err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return false, -1, nil
} else {
return false, 0, err
}
}
return true, httpData.StatusCode, nil
}
80 changes: 80 additions & 0 deletions task2/internal/server/handlers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package server

import (
b64 "encoding/base64"
"encoding/json"
"fmt"
"io"
"math/rand"
"net/http"
"time"
)

type InputJson struct {
InputString string `json:"inputString"`
}

type OutputJson struct {
OutputString string `json:"outputString"`
}

func GetVersion(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Error:", http.StatusMethodNotAllowed)
return
}
w.Header().Set("Version", "1.0.0")
fmt.Println(w.Header().Get("Version"))
}

func Decode(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Error:", http.StatusMethodNotAllowed)
return
}
data, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error:", http.StatusBadRequest)
return
}
var input InputJson
err = json.Unmarshal(data, &input)
if err != nil {
http.Error(w, "Error:", 500)
return
}
decoded, _ := b64.StdEncoding.DecodeString(input.InputString)
output := OutputJson{
OutputString: string(decoded),
}
w.Header().Set("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(output)

if err != nil {
http.Error(w, "Error:", 500)
return
}
}

func HardOp(w http.ResponseWriter, r *http.Request) {
rand.Seed(time.Now().UnixNano())
randomTime := rand.Intn(11) + 10
time.Sleep(time.Duration(randomTime) * time.Second)

badStatuses := []int{
http.StatusBadGateway,
http.StatusGatewayTimeout,
http.StatusHTTPVersionNotSupported,
http.StatusInsufficientStorage,
http.StatusInternalServerError,
http.StatusLoopDetected,
http.StatusNetworkAuthenticationRequired,
}
randomTmp := rand.Intn(2)
if randomTmp == 0 {
w.WriteHeader(http.StatusOK)
} else {
randomBadStatus := rand.Intn(len(badStatuses))
w.WriteHeader(badStatuses[randomBadStatus])
}
}