From 7ef80e84bfdc93f27e4e832cb8c64ec14d9d6553 Mon Sep 17 00:00:00 2001 From: Gustavo Kuklinski Date: Sat, 16 Feb 2019 19:31:57 -0200 Subject: [PATCH 1/2] =?UTF-8?q?Tradu=C3=A7=C3=A3o=20ddas=20Concorrencias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit tradução da páginas de concorrencias em Go --- pt-br/02.7.md | 96 +++++++++++++++++++++++++-------------------------- 1 file changed, 48 insertions(+), 48 deletions(-) diff --git a/pt-br/02.7.md b/pt-br/02.7.md index dd6ecf52..e97dabb5 100644 --- a/pt-br/02.7.md +++ b/pt-br/02.7.md @@ -1,16 +1,16 @@ -# Concurrency +# Concorrência -It is said that Go is the C language of the 21st century. I think there are two reasons: first, Go is a simple language; second, concurrency is a hot topic in today's world, and Go supports this feature at the language level. +Diz-se que Go é a linguagem C do século XXI. Eu acho que existem duas razões: primeiro, o Go é uma linguagem simples; segundo, a simultaneidade é um tema importante no mundo atual, e o Go suporta esse recurso no nível da linguagem. ## goroutine -goroutines and concurrency are built into the core design of Go. They're similar to threads but work differently. More than a dozen goroutines maybe only have 5 or 6 underlying threads. Go also gives you full support to sharing memory in your goroutines. One goroutine usually uses 4~5 KB of stack memory. Therefore, it's not hard to run thousands of goroutines on a single computer. A goroutine is more lightweight, more efficient and more convenient than system threads. +goroutines e simultaneidade são incorporados ao design central do Go. Eles são semelhantes aos tópicos, mas funcionam de maneira diferente. Mais de uma dúzia de goroutines talvez tenham apenas 5 ou 6 threads subjacentes. Go também lhe dá suporte total para compartilhar memória em seus goroutines. Uma goroutine geralmente usa 4 ~ 5 KB de memória de pilha. Portanto, não é difícil executar milhares de goroutines em um único computador. Uma goroutine é mais leve, mais eficiente e mais conveniente que os threads do sistema. -goroutines run on the thread manager at runtime in Go. We use the `go` keyword to create a new goroutine, which is a function at the underlying level ( ***main() is a goroutine*** ). +Os goroutines são executados no gerenciador de encadeamentos em tempo de execução no Go. Usamos a palavra-chave `go` para criar uma nova goroutine, que é uma função no nível subjacente (*** main () é uma goroutine ***). go hello(a, b, c) -Let's see an example. +Vamos ao exemplo: package main @@ -31,7 +31,7 @@ Let's see an example. say("hello") // current goroutine } -Output: +Retorno hello world @@ -43,26 +43,26 @@ Output: world hello -We see that it's very easy to use concurrency in Go by using the keyword `go`. In the above example, these two goroutines share some memory, but we would better off following the design recipe: Don't use shared data to communicate, use communication to share data. +Vemos que é muito fácil usar a simultaneidade no Go usando a palavra-chave `go`. No exemplo acima, essas duas goroutines compartilham alguma memória, mas seria melhor seguir a receita de design: Não use dados compartilhados para se comunicar, use a comunicação para compartilhar dados. -runtime.Gosched() means let the CPU execute other goroutines, and come back at some point. +runtime.Gosched () significa deixar a CPU executar outras goroutines e voltar em algum momento. -The scheduler only uses one thread to run all goroutines, which means it only implements concurrency. If you want to use more CPU cores in order to take advantage of parallel processing, you have to call runtime.GOMAXPROCS(n) to set the number of cores you want to use. If `n<1`, it changes nothing. This function may be removed in the future, see more details about parallel processing and concurrency in this [article](http://concur.rspace.googlecode.com/hg/talk/concur.html#landing-slide). +O agendador usa apenas um thread para executar todos os goroutines, o que significa que ele apenas implementa a simultaneidade. Se você deseja usar mais núcleos de CPU para aproveitar o processamento paralelo, é necessário chamar runtime.GOMAXPROCS (n) para definir o número de núcleos que deseja usar. Se `n <1`, nada muda. Esta função pode ser removida no futuro, veja mais detalhes sobre o processamento paralelo e simultaneidade neste [artigo(em inglês)](http://concur.rspace.googlecode.com/hg/talk/concur.html#landing-slide). -## channels +## Canais(Channels) -goroutines run in the same memory address space, so you have to maintain synchronization when you want to access shared memory. How do you communicate between different goroutines? Go uses a very good communication mechanism called `channel`. `channel` is like a two-way pipeline in Unix shells: use `channel` to send or receive data. The only data type that can be used in channels is the type `channel` and the keyword `chan`. Be aware that you have to use `make` to create a new `channel`. +Os goroutines são executados no mesmo espaço de endereço de memória, portanto, você precisa manter a sincronização quando quiser acessar a memória compartilhada. Como você se comunica entre diferentes goroutines? Go usa um mecanismo de comunicação muito bom chamado `channel`. `channel` é como um pipeline bidirecional em shells Unix: use` channel` para enviar ou receber dados. O único tipo de dado que pode ser usado em canais é o tipo `channel` e a palavra-chave` chan`. Esteja ciente de que você tem que usar `make` para criar um novo` channel`. ci := make(chan int) cs := make(chan string) cf := make(chan interface{}) -channel uses the operator `<-` to send or receive data. +canais usa, o operador `<-` para enviar ou receber dados. - ch <- v // send v to channel ch. - v := <-ch // receive data from ch, and assign to v + ch <- v // envia v para o canal ch. + v := <-ch // recebe dados de ch, e os assina em v -Let's see more examples. +Exemplos: package main @@ -73,7 +73,7 @@ Let's see more examples. for _, v := range a { total += v } - c <- total // send total to c + c <- total // envia o total para c } func main() { @@ -82,39 +82,39 @@ Let's see more examples. c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) - x, y := <-c, <-c // receive from c + x, y := <-c, <-c // recebe de c fmt.Println(x, y, x + y) } -Sending and receiving data in channels blocks by default, so it's much easier to use synchronous goroutines. What I mean by block is that a goroutine will not continue when receiving data from an empty channel, i.e (`value := <-ch`), until other goroutines send data to this channel. On the other hand, the goroutine will not continue until the data it sends to a channel, i.e (`ch<-5`), is received. +Enviando e recebendo dados em blocos de canais por padrão, é muito mais fácil usar goroutines síncronas. O que quero dizer com block é que uma goroutine não continuará ao receber dados de um canal vazio, ou seja, (`value: = <-ch`), até que outras goroutines enviem dados para este canal. Por outro lado, a goroutine não continuará até que os dados enviados a um canal, ou seja (`ch <-5`), sejam recebidos. -## Buffered channels +## Canais em Buffer -I introduced non-buffered channels above. Go also has buffered channels that can store more than a single element. For example, `ch := make(chan bool, 4)`, here we create a channel that can store 4 boolean elements. So in this channel, we are able to send 4 elements into it without blocking, but the goroutine will be blocked when you try to send a fifth element and no goroutine receives it. +Eu introduzi canais não-bufferizados acima. Go também tem canais em buffer que podem armazenar mais de um único elemento. Por exemplo, `ch: = make (chan bool, 4)`, aqui criamos um canal que pode armazenar 4 elementos booleanos. Assim, neste canal, podemos enviar 4 elementos sem bloqueio, mas a goroutine será bloqueada quando você tentar enviar um quinto elemento e nenhuma goroutine o receber. ch := make(chan type, n) n == 0 ! non-buffer(block) n > 0 ! buffer(non-block until n elements in the channel) -You can try the following code on your computer and change some values. +Você pode tentar o seguinte código no seu computador e alterar alguns valores. package main import "fmt" func main() { - c := make(chan int, 2) // change 2 to 1 will have runtime error, but 3 is fine + c := make(chan int, 2) // altera de 2 para 1 e retornará um erro, mas 3 funciona c <- 1 c <- 2 fmt.Println(<-c) fmt.Println(<-c) } -## Range and Close +## Alcance e fechamento(Range and Close) -We can use range to operate on buffer channels as in slice and map. +Podemos usar o range para operar em canais buffer como em slice e map. package main @@ -139,17 +139,17 @@ We can use range to operate on buffer channels as in slice and map. } } -`for i := range c` will not stop reading data from channel until the channel is closed. We use the keyword `close` to close the channel in above example. It's impossible to send or receive data on a closed channel; you can use `v, ok := <-ch` to test if a channel is closed. If `ok` returns false, it means the there is no data in that channel and it was closed. +`for i := range c` não parará de ler dados do canal até que o canal seja fechado. Usamos a palavra-chave `close` para fechar o canal no exemplo acima. É impossível enviar ou receber dados em um canal fechado; você pode usar `v, ok: = <-ch` para testar se um canal está fechado. Se `ok` retornar falso, significa que não há dados nesse canal e foi fechado. -Remember to always close channels in producers and not in consumers, or it's very easy to get into panic status. +Lembre-se sempre de fechar os canais nos produtores e não nos consumidores, ou é muito fácil entrar em status de pânico. -Another thing you need to remember is that channels are not like files. You don't have to close them frequently unless you are sure the channel is completely useless, or you want to exit range loops. +Outra coisa que você precisa lembrar é que os canais não são como arquivos. Você não precisa fechá-los com frequência, a menos que tenha certeza de que o canal é completamente inútil ou deseja sair de loops de intervalo. ## Select -In the above examples, we only use one channel, but how can we deal with more than one channel? Go has a keyword called `select` to listen to many channels. +Nos exemplos acima, usamos apenas um canal, mas como podemos lidar com mais de um canal? Go tem uma palavra-chave chamada `select` para ouvir muitos canais. -`select` is blocking by default and it continues to execute only when one of channels has data to send or receive. If several channels are ready to use at the same time, select chooses which to execute randomly. +`select` está bloqueando por padrão e continua a executar somente quando um dos canais tem dados para enviar ou receber. Se vários canais estiverem prontos para usar ao mesmo tempo, selecione a opção para executar aleatoriamente. package main @@ -180,18 +180,18 @@ In the above examples, we only use one channel, but how can we deal with more th fibonacci(c, quit) } -`select` has a `default` case as well, just like `switch`. When all the channels are not ready for use, it executes the default case (it doesn't wait for the channel anymore). +`select` tem um caso` default`, assim como `switch`. Quando todos os canais não estão prontos para uso, ele executa o caso padrão (ele não aguarda mais o canal). select { case i := <-c: // use i default: - // executes here when c is blocked + // Executa aqui quando C estiver bloqueado } ## Timeout -Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whole program from blocking? It's simple, we can set a timeout in the select. +Às vezes uma goroutine fica bloqueada. Como podemos evitar isso para evitar que todo o programa bloqueie? É simples, podemos definir um tempo limite no select. func main() { c := make(chan int) @@ -213,30 +213,30 @@ Sometimes a goroutine becomes blocked. How can we avoid this to prevent the whol ## Runtime goroutine -The package `runtime` has some functions for dealing with goroutines. +O pacote `runtime` tem algumas funções para lidar com goroutines. -- `runtime.Goexit()` +- `runtime.Goexit ()` - Exits the current goroutine, but defered functions will be executed as usual. - -- `runtime.Gosched()` +Sai da gorout atual, mas as funções adiadas serão executadas como de costume. - Lets the scheduler execute other goroutines and comes back at some point. - -- `runtime.NumCPU() int` +- `runtime.Gosched ()` - Returns the number of CPU cores +Permite que o planejador execute outras goroutines e volte em algum momento. -- `runtime.NumGoroutine() int` +- `runtime.NumCPU () int` - Returns the number of goroutines +Retorna o número de núcleos da CPU -- `runtime.GOMAXPROCS(n int) int` +- `runtime.NumGoroutine () int` - Sets how many CPU cores you want to use +Retorna o número de goroutines + +- `runtime.GOMAXPROCS (n int) int` + +Define quantos núcleos de CPU você deseja usar ## Links -- [Directory](preface.md) -- Previous section: [interface](02.6.md) -- Next section: [Summary](02.8.md) +- [Prefácio](preface.md) +- Seção anterior: [interfaces](02.6.md) +- Próxima seção: [Summary](02.8.md) From 3aadb905c3fafed7629947a2d05940bd1a5e1c16 Mon Sep 17 00:00:00 2001 From: gustavokuklinski Date: Sat, 16 Feb 2019 20:29:15 -0200 Subject: [PATCH 2/2] 03.1 principios da web --- pt-br/03.1.md | 138 +++++++++++++++++++++++++------------------------- 1 file changed, 70 insertions(+), 68 deletions(-) diff --git a/pt-br/03.1.md b/pt-br/03.1.md index ca91cd86..fc2ea545 100644 --- a/pt-br/03.1.md +++ b/pt-br/03.1.md @@ -1,77 +1,77 @@ -# Web working principles +# Principios da Web -Every time you open your browsers, type some URLs and press enter, you will see beautiful web pages appear on your screen. But do you know what is happening behind these simple actions? +Toda vez que você abrir seus navegadores, digite alguns URLs e pressione enter, você verá lindas páginas da web aparecerem na tela. Mas você sabe o que está acontecendo por trás dessas ações simples? -Normally, your browser is a client. After you type a URL, it takes the host part of the URL and sends it to a DNS server in order to get the IP address of the host. Then it connects to the IP address and asks to setup a TCP connection. The browser sends HTTP requests through the connection. The server handles them and replies with HTTP responses containing the content that make up the web page. Finally, the browser renders the body of the web page and disconnects from the server. +Normalmente, seu navegador é um cliente. Depois de digitar um URL, ele pega a parte do host do URL e a envia para um servidor DNS para obter o endereço IP do host. Em seguida, ele se conecta ao endereço IP e solicita a configuração de uma conexão TCP. O navegador envia solicitações HTTP por meio da conexão. O servidor lida com eles e responde com respostas HTTP contendo o conteúdo que compõe a página da web. Por fim, o navegador renderiza o corpo da página da Web e se desconecta do servidor. ![](images/3.1.web2.png?raw=true) -Figure 3.1 Processes of users visit a website +Imagem: 3.1 Processo dos usuários visitando um site -A web server, also known as an HTTP server, uses the HTTP protocol to communicate with clients. All web browsers can be considered clients. +Um servidor da Web, também conhecido como servidor HTTP, usa o protocolo HTTP para se comunicar com os clientes. Todos os navegadores da web podem ser considerados clientes. -We can divide the web's working principles into the following steps: +Podemos dividir os princípios de trabalho da Web nas seguintes etapas: -- Client uses TCP/IP protocol to connect to server. -- Client sends HTTP request packages to server. -- Server returns HTTP response packages to client. If the requested resources include dynamic scripts, server calls script engine first. -- Client disconnects from server, starts rendering HTML. +- Cliente usa o protocolo TCP / IP para se conectar ao servidor. +- Cliente envia pacotes de solicitações HTTP para o servidor. +- O servidor retorna pacotes de resposta HTTP ao cliente. Se os recursos solicitados incluírem scripts dinâmicos, o mecanismo de script de chamadas do servidor será o primeiro. +- Cliente se desconecta do servidor, começa a renderizar HTML. -This is a simple work flow of HTTP affairs -notice that the server closes its connections after it sends data to the clients, then waits for the next request. +Este é um fluxo de trabalho simples de assuntos HTTP - observe que o servidor fecha suas conexões depois de enviar dados para os clientes e aguarda a próxima solicitação. -## URL and DNS resolution +## Resolvendo URL e DNS -We always use URLs to access web pages, but do you know how URLs work? +Nós sempre usamos URLs para acessar páginas da web, mas você sabe como funcionam os URLs? -The full name of a URL is Uniform Resource Locator. It's for describing resources on the internet and its basic form is as follows. +O nome completo de uma URL é Uniform Resource Locator. É para descrever recursos na internet e sua forma básica é a seguinte. scheme://host[:port#]/path/.../[?query-string][#anchor] - scheme assign underlying protocol (such as HTTP, HTTPS, FTP) - host IP or domain name of HTTP server - port# default port is 80, and it can be omitted in this case. If you want to use other ports, you must specify which port. For example, http://www.cnblogs.com:8080/ - path resources path - query-string data are sent to server - anchor anchor + scheme Define o protocolo a ser utilizado (Ex: HTTP, HTTPS, FTP) + host IP ou nome do domínino do servidor HTTP + port# a porta padrão é 80 e pode ser omitida nesse caso. Se você quiser usar outras portas, você deve especificar qual porta. Por exemplo, http://www.cnblogs.com:8080/ + path Caminho + query-string Dados enviados através da URI + anchor Âncora -DNS is an abbreviation of Domain Name System. It's the naming system for computer network services, and it converts domain names to actual IP addresses, just like a translator. +DNS é uma abreviação de Domain Name System. É o sistema de nomes para serviços de rede de computadores e converte nomes de domínio em endereços IP reais, exatamente como um tradutor. ![](images/3.1.dns_hierachy.png?raw=true) -Figure 3.2 DNS working principles +Imagem 3.2 Principios do DNS -To understand more about its working principle, let's see the detailed DNS resolution process as follows. +Para entender mais sobre seu princípio de funcionamento, vamos ver o processo detalhado de resolução de DNS como segue. -1. After typing the domain name `www.qq.com` in the browser, the operating system will check if there are any mapping relationships in the hosts' files for this domain name. If so, then the domain name resolution is complete. -2. If no mapping relationships exist in the hosts' files, the operating system will check if any cache exists in the DNS. If so, then the domain name resolution is complete. -3. If no mapping relationships exist in both the host and DNS cache, the operating system finds the first DNS resolution server in your TCP/IP settings, which is likely your local DNS server. When the local DNS server receives the query, if the domain name that you want to query is contained within the local configuration of its regional resources, it returns the results to the client. This DNS resolution is authoritative. -4. If the local DNS server doesn't contain the domain name but a mapping relationship exists in the cache, the local DNS server gives back this result to the client. This DNS resolution is not authoritative. -5. If the local DNS server cannot resolve this domain name either by configuration of regional resources or cache, it will proceed to the next step, which depends on the local DNS server's settings. --If the local DNS server doesn't enable forwarding, it routes the request to the root DNS server, then returns the IP address of a top level DNS server which may know the domain name, `.com` in this case. If the first top level DNS server doesn't recognize the domain name, it again reroutes the request to the next top level DNS server until it reaches one that recognizes the domain name. Then the top level DNS server asks this next level DNS server for the IP address corresponding to `www.qq.com`. --If the local DNS server has forwarding enabled, it sends the request to an upper level DNS server. If the upper level DNS server also doesn't recognize the domain name, then the request keeps getting rerouted to higher levels until it finally reaches a DNS server which recognizes the domain name. +1. Depois de digitar o nome de domínio `www.qq.com` no navegador, o sistema operacional verificará se há algum relacionamento de mapeamento nos arquivos dos hosts para este nome de domínio. Em caso afirmativo, a resolução do nome de domínio será concluída. +2. Se não existirem relacionamentos de mapeamento nos arquivos dos hosts, o sistema operacional verificará se existe algum cache no DNS. Em caso afirmativo, a resolução do nome de domínio será concluída. +3. Se não existirem relações de mapeamento no host e no cache DNS, o sistema operacional localizará o primeiro servidor de resolução de DNS nas configurações de TCP / IP, o que provavelmente é o servidor DNS local. Quando o servidor DNS local recebe a consulta, se o nome de domínio que você deseja consultar estiver contido na configuração local de seus recursos regionais, ele retornará os resultados para o cliente. Essa resolução de DNS é autoritativa. +4. Se o servidor DNS local não contiver o nome de domínio, mas existir um relacionamento de mapeamento no cache, o servidor DNS local devolverá esse resultado ao cliente. Essa resolução de DNS não é autoritativa. +5. Se o servidor DNS local não puder resolver esse nome de domínio por meio da configuração de recursos regionais ou do cache, ele prosseguirá para a próxima etapa, que depende das configurações do servidor DNS local. +- Se o servidor DNS local não habilitar o encaminhamento, ele encaminhará a solicitação para o servidor DNS raiz e, em seguida, retornará o endereço IP de um servidor DNS de nível superior que pode saber o nome do domínio, `.com` neste caso. Se o primeiro servidor DNS de nível superior não reconhecer o nome de domínio, ele redireciona novamente a solicitação para o próximo servidor DNS de nível superior até que ele atinja um que reconheça o nome do domínio. Em seguida, o servidor DNS de nível superior solicita a este servidor DNS de nível seguinte o endereço IP correspondente a `www.qq.com`. +-Se o servidor DNS local tiver o encaminhamento ativado, ele enviará a solicitação para um servidor DNS de nível superior. Se o servidor DNS de nível superior também não reconhecer o nome de domínio, a solicitação continuará sendo reencaminhada para níveis mais altos até que finalmente chegue a um servidor DNS que reconheça o nome do domínio. -Whether or not the local DNS server enables forwarding, the IP address of the domain name always returns to the local DNS server, and the local DNS server sends it back to the client. +Independentemente de o servidor DNS local permitir ou não o encaminhamento, o endereço IP do nome de domínio sempre retornará ao servidor DNS local e o servidor DNS local o enviará de volta ao cliente. ![](images/3.1.dns_inquery.png?raw=true) -Figure 3.3 DNS resolution work flow +Imagem 3.3 Caminhos do fluxo DNS -`Recursive query process` simply means that the enquirers change in the process. Enquirers do not change in `Iterative query` processes. +`Processo de consulta recursiva` significa simplesmente que os inquiridores mudam no processo. Os inquiridores não mudam nos processos de consulta iterativa. -Now we know clients get IP addresses in the end, so the browsers are communicating with servers through IP addresses. +Agora sabemos que os clientes obtêm endereços IP no final, portanto, os navegadores estão se comunicando com servidores por meio de endereços IP. -## HTTP protocol +## Protocolo HTTP -The HTTP protocol is a core part of web services. It's important to know what the HTTP protocol is before you understand how the web works. +O protocolo HTTP é uma parte essencial dos serviços da web. É importante saber o que é o protocolo HTTP antes de entender como a Web funciona. -HTTP is the protocol that is used to facilitate communication between browsers and web servers. It is based on the TCP protocol and usually uses port 80 on the side of the web server. It is a protocol that utilizes the request-response model -clients send requests and servers respond. According to the HTTP protocol, clients always setup new connections and send HTTP requests to servers. Servers are not able to connect to clients proactively, or establish callback connections. The connection between a client and a server can be closed by either side. For example, you can cancel your download request and HTTP connection and your browser will disconnect from the server before you finish downloading. +HTTP é o protocolo usado para facilitar a comunicação entre navegadores e servidores da web. Ele é baseado no protocolo TCP e geralmente usa a porta 80 no lado do servidor da web. É um protocolo que utiliza o modelo de solicitação-resposta - os clientes enviam solicitações e os servidores respondem. De acordo com o protocolo HTTP, os clientes sempre configuram novas conexões e enviam solicitações HTTP para os servidores. Os servidores não podem se conectar aos clientes de maneira proativa ou estabelecer conexões de retorno de chamada. A conexão entre um cliente e um servidor pode ser fechada por qualquer um dos lados. Por exemplo, você pode cancelar sua solicitação de download e a conexão HTTP e seu navegador desconectará do servidor antes de concluir o download. -The HTTP protocol is stateless, which means the server has no idea about the relationship between the two connections even though they are both from same client. To solve this problem, web applications use cookies to maintain the state of connections. +O protocolo HTTP é sem estado, o que significa que o servidor não tem idéia sobre o relacionamento entre as duas conexões, embora sejam do mesmo cliente. Para resolver esse problema, os aplicativos da Web usam cookies para manter o estado das conexões. -Because the HTTP protocol is based on the TCP protocol, all TCP attacks will affect HTTP communications in your server. Examples of such attacks are SYN flooding, DoS and DDoS attacks. +Como o protocolo HTTP é baseado no protocolo TCP, todos os ataques TCP afetarão as comunicações HTTP em seu servidor. Exemplos de tais ataques são inundações SYN, ataques DoS e DDoS. -### HTTP request package (browser information) +### Pacote de request HTTP (informação do browser) -Request packages all have three parts: request line, request header, and body. There is one blank line between header and body. +Todos os pacotes de solicitação têm três partes: linha de solicitação, cabeçalho de solicitação e corpo. Há uma linha em branco entre o cabeçalho e o corpo. GET /domains/example/ HTTP/1.1 // request line: request method, URL, protocol and its version Host:www.iana.org // domain name @@ -82,23 +82,25 @@ Request packages all have three parts: request line, request header, and body. T // blank line // body, request resource arguments (for example, arguments in POST) -We use fiddler to get the following request information. +Usamos fiddler para obter as seguintes informações de solicitação. ![](images/3.1.http.png?raw=true) -Figure 3.4 Information of a GET request caught by fiddler +Imagem 3.4 Informação de um GET request mostrado pelo fiddler ![](images/3.1.httpPOST.png?raw=true) -Figure 3.5 Information of a POST request caught by fiddler +Imagem 3.5 Informação de um POST request mostrado pelo fiddler **We can see that GET does not have a request body, unlike POST, which does.** -There are many methods you can use to communicate with servers in HTTP; GET, POST, PUT and DELETE are the 4 basic methods that we typically use. A URL represents a resource on a network, so these 4 methods define the query, change, add and delete operations that can act on these resources. GET and POST are very commonly used in HTTP. GET can append query parameters to the URL, using `?` to separate the URL and parameters and `&` between the arguments, like `EditPosts.aspx?name=test1&id=123456`. POST puts data in the request body because the URL implements a length limitation via the browser. Thus, POST can submit much more data than GET. Also, when we submit user names and passwords, we don't want this kind of information to appear in the URL, so we use POST to keep them invisible. +** Podemos ver que o GET não tem um corpo de solicitação, ao contrário do POST, que faz. ** -### HTTP response package (server information) +Existem muitos métodos que você pode usar para se comunicar com servidores em HTTP; GET, POST, PUT e DELETE são os 4 métodos básicos que normalmente usamos. Uma URL representa um recurso em uma rede, portanto, esses quatro métodos definem a consulta, alteram, adicionam e excluem operações que podem atuar nesses recursos. GET e POST são muito usados em HTTP. GET pode anexar parâmetros de consulta à URL, usando `?` Para separar a URL e os parâmetros e `&` entre os argumentos, como `EditPosts.aspx?name=test1&id=123456`. O POST coloca dados no corpo da solicitação porque o URL implementa uma limitação de tamanho por meio do navegador. Assim, o POST pode enviar muito mais dados do que o GET. Além disso, quando enviamos nomes de usuário e senhas, não queremos que esse tipo de informação apareça no URL. Por isso, usamos o POST para mantê-los invisíveis. -Let's see what information is contained in the response packages. +### HTTP response package (informação do servidor) + +Vamos ver quais informações estão contidas nos pacotes de resposta. HTTP/1.1 200 OK // status line Server: nginx/1.0.8 // web server software and its version in the server machine @@ -110,44 +112,44 @@ Let's see what information is contained in the response packages. // blank line