03.1 principios da web

This commit is contained in:
gustavokuklinski
2019-02-16 20:29:15 -02:00
parent 7ef80e84bf
commit 3aadb905c3

View File

@@ -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) ![](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. - Cliente usa o protocolo TCP / IP para se conectar ao servidor.
- Client sends HTTP request packages to server. - Cliente envia pacotes de solicitações HTTP para o servidor.
- Server returns HTTP response packages to client. If the requested resources include dynamic scripts, server calls script engine first. - 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.
- Client disconnects from server, starts rendering HTML. - 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://host[:port#]/path/.../[?query-string][#anchor]
scheme assign underlying protocol (such as HTTP, HTTPS, FTP) scheme Define o protocolo a ser utilizado (Ex: HTTP, HTTPS, FTP)
host IP or domain name of HTTP server host IP ou nome do domínino do servidor HTTP
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/ 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 resources path path Caminho
query-string data are sent to server query-string Dados enviados através da URI
anchor anchor 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) ![](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. 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. 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. 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. 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. 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. 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. 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. 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. 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.
-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`. - 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`.
-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. -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) ![](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 GET /domains/example/ HTTP/1.1 // request line: request method, URL, protocol and its version
Hostwww.iana.org // domain name Hostwww.iana.org // domain name
@@ -82,23 +82,25 @@ Request packages all have three parts: request line, request header, and body. T
// blank line // blank line
// body, request resource arguments (for example, arguments in POST) // 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) ![](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) ![](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.** **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 HTTP/1.1 200 OK // status line
Server: nginx/1.0.8 // web server software and its version in the server machine 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 // blank line
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"... // message body <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"... // message body
The first line is called the status line. It supplies the HTTP version, status code and status message. A primeira linha é chamada de linha de status. Ele fornece a versão HTTP, o código de status e a mensagem de status.
The status code informs the client of the status of the HTTP server's response. In HTTP/1.1, 5 kinds of status codes were defined: O código de status informa ao cliente o status da resposta do servidor HTTP. No HTTP / 1.1, 5 tipos de códigos de status foram definidos:
- 1xx Informational - 1xx Informação
- 2xx Success - 2xx Sucesso
- 3xx Redirection - 3xx Redirecionamento
- 4xx Client Error - 4xx Erro ao lado Cliente(ex: 404)
- 5xx Server Error - 5xx Erro ao lado do servidor (ex: 502)
Let's see more examples about response packages. 200 means server responded correctly, 302 means redirection. Vamos ver mais exemplos sobre pacotes de resposta. 200 significa que o servidor respondeu corretamente, 302 significa redirecionamento.
![](images/3.1.response.png?raw=true) ![](images/3.1.response.png?raw=true)
Figure 3.6 Full information for visiting a website Imagem 3.6 Informação completa de um site
### HTTP is stateless and Connection: keep-alive ### HTTP é stateless e conexão: keep-alive
The term stateless doesn't mean that the server has no ability to keep a connection. It simply means that the server doesn't recognize any relationships between any two requests. O termo stateless não significa que o servidor não tenha capacidade de manter uma conexão. Significa simplesmente que o servidor não reconhece nenhum relacionamento entre duas solicitações.
In HTTP/1.1, Keep-alive is used by default. If clients have additional requests, they will use the same connection for them. No HTTP / 1.1, o Keep-alive é usado por padrão. Se os clientes tiverem solicitações adicionais, eles usarão a mesma conexão para eles.
Notice that Keep-alive cannot maintian one connection forever; the application running in the server determines the limit with which to keep the connection alive for, and in most cases you can configure this limit. Observe que o Keep-alive não pode manter uma conexão para sempre; o aplicativo em execução no servidor determina o limite com o qual manter a conexão ativa e, na maioria dos casos, você pode configurar esse limite.
## Request instance ## Instancia de requisição
![](images/3.1.web.png?raw=true) ![](images/3.1.web.png?raw=true)
Figure 3.7 All packages for opening one web page Imagem 3.7 Todos os pacotes
We can see the entire communication process between client and server from the above picture. You may notice that there are many resource files in the list; these are called static files, and Go has specialized processing methods for these files. Podemos ver todo o processo de comunicação entre cliente e servidor da figura acima. Você pode perceber que há muitos arquivos de recursos na lista; esses são chamados de arquivos estáticos e o Go especializou-se em métodos de processamento para esses arquivos.
This is the most important function of browsers: to request for a URL and retrieve data from web servers, then render the HTML. If it finds some files in the DOM such as CSS or JS files, browsers will request these resources from the server again until all the resources finish rendering on your screen. Essa é a função mais importante dos navegadores: solicitar uma URL e recuperar dados de servidores da Web e renderizar o HTML. Se encontrar alguns arquivos no DOM, como arquivos CSS ou JS, os navegadores solicitarão esses recursos do servidor novamente até que todos os recursos concluam a renderização na tela.
Reducing HTTP request times is one way of improving the loading speed of web pages. By reducing the number of CSS and JS files that need to be loaded, both request latencies and pressure on your web servers can be reduced at the same time. Reduzir os tempos de solicitação de HTTP é uma maneira de melhorar a velocidade de carregamento de páginas da web. Ao reduzir o número de arquivos CSS e JS que precisam ser carregados, as latências de solicitação e a pressão nos servidores da Web podem ser reduzidas ao mesmo tempo.
## Links ## Links
- [Directory](preface.md) - [Sumário](preface.md)
- Previous section: [Web foundation](03.0.md) - Seção anterior: [Fundamentos da Web](03.0.md)
- Next section: [Build a simple web server](03.2.md) - Próxima seção: [Construindo um servidor web simples](03.2.md)