From 19d79613cdd64e9b9b8a41daee8c055d34520ef7 Mon Sep 17 00:00:00 2001 From: Fedor Korotkiy Date: Thu, 2 Apr 2020 17:01:16 +0300 Subject: [PATCH] Fit slides to screen --- .../context/cancelation/cancelation.go | 5 +- .../06-http/context/httpserver/handler.go | 1 - lectures/06-http/customclient/customclient.go | 9 ---- lectures/06-http/custompost/custompost.go | 5 +- .../gracefulshutdown/gracefulshutdown.go | 13 ++--- lectures/06-http/httptest/code.go | 19 +++---- .../06-http/keepalive/advanced/advanced.go | 9 +--- lectures/06-http/keepalive/correct/correct.go | 7 +-- lectures/06-http/lecture.slide | 50 ++++++++++++++----- lectures/06-http/simpleget/simpleget.go | 1 + lectures/06-http/simpleserver/router.go | 2 - 11 files changed, 59 insertions(+), 62 deletions(-) diff --git a/lectures/06-http/context/cancelation/cancelation.go b/lectures/06-http/context/cancelation/cancelation.go index a5f34c2..3a4939e 100644 --- a/lectures/06-http/context/cancelation/cancelation.go +++ b/lectures/06-http/context/cancelation/cancelation.go @@ -8,7 +8,6 @@ import ( func SimpleCancelation() { ctx, cancel := context.WithCancel(context.Background()) defer cancel() - go func() { time.Sleep(5 * time.Second) cancel() @@ -19,6 +18,8 @@ func SimpleCancelation() { } } +// OMIT + func SimpleTimeout() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() @@ -28,6 +29,8 @@ func SimpleTimeout() { } } +// OMIT + func doSlowJob(ctx context.Context) error { for { select { diff --git a/lectures/06-http/context/httpserver/handler.go b/lectures/06-http/context/httpserver/handler.go index 9a084c4..c04990f 100644 --- a/lectures/06-http/context/httpserver/handler.go +++ b/lectures/06-http/context/httpserver/handler.go @@ -22,7 +22,6 @@ func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { defer fd.Close() scanner := bufio.NewScanner(fd) - for scanner.Scan() { select { case <-ctx.Done(): diff --git a/lectures/06-http/customclient/customclient.go b/lectures/06-http/customclient/customclient.go index 79a0b74..61797a3 100644 --- a/lectures/06-http/customclient/customclient.go +++ b/lectures/06-http/customclient/customclient.go @@ -3,7 +3,6 @@ package main import ( "crypto/tls" "crypto/x509" - "errors" "net/http" "net/http/cookiejar" "time" @@ -13,16 +12,9 @@ func main() { // все куки записанные в этот Jar будут передаваться // и изменяться во всех запросах cj, _ := cookiejar.New(nil) - client := &http.Client{ Timeout: 1 * time.Second, Jar: cj, - CheckRedirect: func(req *http.Request, via []*http.Request) error { - if len(via) > 20 { - return errors.New("too many redirects") - } - return nil - }, Transport: &http.Transport{ // резмер буферов чтения и записи (4KB по-умолчанию) WriteBufferSize: 32 << 10, @@ -38,6 +30,5 @@ func main() { // ... }, } - _ = client } diff --git a/lectures/06-http/custompost/custompost.go b/lectures/06-http/custompost/custompost.go index 824988d..5e337d2 100644 --- a/lectures/06-http/custompost/custompost.go +++ b/lectures/06-http/custompost/custompost.go @@ -10,13 +10,12 @@ import ( func main() { body := bytes.NewBufferString("All your base are belong to us") - req, err := http.NewRequest("POST", "https://myapi.com/create", body) + req, err := http.NewRequest(http.MethodPost, "https://myapi.com/create", body) if err != nil { log.Fatal(err) } req.Header.Set("X-Source", "Zero Wing") - repr, err := httputil.DumpRequestOut(req, true) if err == nil { fmt.Println(string(repr)) @@ -26,6 +25,6 @@ func main() { if err != nil { log.Fatal(err) } - + defer resp.Body.Close() fmt.Println(resp.StatusCode) } diff --git a/lectures/06-http/gracefulshutdown/gracefulshutdown.go b/lectures/06-http/gracefulshutdown/gracefulshutdown.go index 05d64b5..8e44aa3 100644 --- a/lectures/06-http/gracefulshutdown/gracefulshutdown.go +++ b/lectures/06-http/gracefulshutdown/gracefulshutdown.go @@ -17,16 +17,15 @@ func main() { } } -func run() error { - handler := func(w http.ResponseWriter, r *http.Request) { - _, _ = w.Write([]byte("pong")) - } +func handler(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte("pong")) +} +func run() error { srv := &http.Server{ Addr: ":8080", Handler: http.HandlerFunc(handler), } - serveChan := make(chan error, 1) go func() { serveChan <- srv.ListenAndServe() @@ -34,15 +33,13 @@ func run() error { stop := make(chan os.Signal, 1) signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM) - select { case <-stop: fmt.Println("shutting down gracefully") - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - return srv.Shutdown(ctx) + case err := <-serveChan: return err } diff --git a/lectures/06-http/httptest/code.go b/lectures/06-http/httptest/code.go index cab3dca..0198526 100644 --- a/lectures/06-http/httptest/code.go +++ b/lectures/06-http/httptest/code.go @@ -7,6 +7,13 @@ import ( "strconv" ) +func NewAPICLient(baseURL string) *APIClient { + if baseURL == "" { + baseURL = BaseURLProd + } + return &APIClient{baseURL: baseURL, httpc: new(http.Client)} +} + const ( BaseURLProd = "https://github.com/api" ) @@ -16,26 +23,14 @@ type APIClient struct { httpc *http.Client } -func NewAPICLient(baseURL string) *APIClient { - if baseURL == "" { - baseURL = BaseURLProd - } - return &APIClient{ - baseURL: baseURL, - httpc: new(http.Client), - } -} - func (c *APIClient) GetReposCount(ctx context.Context, userID string) (int, error) { url := c.baseURL + "/users/" + userID + "/repos/count" req, _ := http.NewRequestWithContext(ctx, "GET", url, nil) - resp, err := c.httpc.Do(req) if err != nil { return 0, err } defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) if err != nil { return 0, err diff --git a/lectures/06-http/keepalive/advanced/advanced.go b/lectures/06-http/keepalive/advanced/advanced.go index 1c2ef50..f696897 100644 --- a/lectures/06-http/keepalive/advanced/advanced.go +++ b/lectures/06-http/keepalive/advanced/advanced.go @@ -9,20 +9,13 @@ import ( func main() { urls := []string{"https://golang.org/doc", "https://golang.org/pkg", "https://golang.org/help"} - client := &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{ - InsecureSkipVerify: true, - }, - }, + Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}, } var wg sync.WaitGroup - for _, url := range urls { wg.Add(1) - go func(url string) { defer wg.Done() resp, err := client.Get(url) diff --git a/lectures/06-http/keepalive/correct/correct.go b/lectures/06-http/keepalive/correct/correct.go index 3503a57..dc919a9 100644 --- a/lectures/06-http/keepalive/correct/correct.go +++ b/lectures/06-http/keepalive/correct/correct.go @@ -11,14 +11,9 @@ import ( func main() { urls := []string{"https://golang.org/doc", "https://golang.org/pkg", "https://golang.org/help"} - client := &http.Client{ - Transport: &http.Transport{ - MaxConnsPerHost: 100, - }, - } + client := &http.Client{Transport: &http.Transport{MaxConnsPerHost: 100}} var wg sync.WaitGroup - for _, url := range urls { wg.Add(1) diff --git a/lectures/06-http/lecture.slide b/lectures/06-http/lecture.slide index 7f6d944..294d894 100644 --- a/lectures/06-http/lecture.slide +++ b/lectures/06-http/lecture.slide @@ -1,7 +1,7 @@ http и context Лекция 6 -Георгий Зуйков +Фёдор Короткий * Имеем из коробки @@ -34,7 +34,7 @@ http и context * Делаем более лучший запрос -.play custompost/custompost.go +.play custompost/custompost.go /func/,/^}/ `http.DefaultClient` - базовый глобальный клиент с настройками по-умолчанию. @@ -87,12 +87,20 @@ http и context .code simpleserver/simpleserver.go /func RunTLSServer/,/^}/ -http.Handler - интерфейс, описывающий функцию для обработки HTTP запроса. +* Простой HTTP сервер + +`http.Handler` - интерфейс, описывающий функцию для обработки HTTP запроса. type Handler interface { ServeHTTP(ResponseWriter, *Request) } + type ResponseWriter interface { + Header() Header + WriteStatus(int) + Write([]byte) (int, error) + } + * Роутинг .code simpleserver/router.go /func RunServerWithRouting/,/OMIT/ @@ -119,10 +127,6 @@ http.Handler - интерфейс, описывающий функцию для * context -Контекст - инкапсулированное состояние определенной части приложения. -Позволяет оповещать операции о необходимости завершения и/или передавать контекстозависимые значения между различными частями приложения. -Контексты наследуемы, при отмене закрывается родительский и все дочерние контексты. - type Context interface { // Возвращает время, когда операция будет оповещена о необходимости завершения Deadline() (deadline time.Time, ok bool) @@ -142,15 +146,37 @@ http.Handler - интерфейс, описывающий функцию для Value(key interface{}) interface{} } -Типы контекстов: -- TODO -- Background -- Cancel -- Deadline +- Отмена таймауты +- Передача request scoped значений +* context + +Типы контекстов: + + // root context + todo := context.TODO() + ctx := context.Background() + + // manual cancel + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + // cancel by timeout + ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) + defer cancel() + + ctx, cancel := context.WithDeadline(ctx, time.Now().Add(time.Second)) + defer cancel() + * Отменяем операции .code context/cancelation/cancelation.go /func SimpleCancelation()/,/OMIT/ +.code context/cancelation/cancelation.go /func doSlowJob/,/OMIT/ + +* Отменяем операции + +.code context/cancelation/cancelation.go /func SimpleTimeout()/,/OMIT/ +.code context/cancelation/cancelation.go /func doSlowJob/,/OMIT/ * context в библиотеках Go diff --git a/lectures/06-http/simpleget/simpleget.go b/lectures/06-http/simpleget/simpleget.go index cab92c8..8662801 100644 --- a/lectures/06-http/simpleget/simpleget.go +++ b/lectures/06-http/simpleget/simpleget.go @@ -10,5 +10,6 @@ func main() { if err != nil { panic(err) } + defer resp.Body.Close() fmt.Println(resp.StatusCode) } diff --git a/lectures/06-http/simpleserver/router.go b/lectures/06-http/simpleserver/router.go index 87e9deb..d2a2432 100644 --- a/lectures/06-http/simpleserver/router.go +++ b/lectures/06-http/simpleserver/router.go @@ -15,7 +15,6 @@ func RunServerWithRouting() { w.WriteHeader(404) } } - err := http.ListenAndServe(":8080", http.HandlerFunc(router)) if err != nil { panic(err) @@ -25,7 +24,6 @@ func RunServerWithRouting() { func pongHandler(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("pong")) } - func shmongHandler(w http.ResponseWriter, r *http.Request) { _, _ = w.Write([]byte("shmong")) }