http сервера

This commit is contained in:
badkaktus 2019-10-12 21:40:43 +03:00
parent 0cffcf4fe6
commit 18cd0d0514
3 changed files with 25 additions and 24 deletions

View File

@ -67,7 +67,7 @@ Epoch
Подкоманды командной строки (Command-Line Subcommands) Подкоманды командной строки (Command-Line Subcommands)
Переменные среды (Environment Variables) Переменные среды (Environment Variables)
HTTP клиенты (HTTP Clients) HTTP клиенты (HTTP Clients)
HTTP Servers HTTP серверы (HTTP Servers)
Spawning Processes Spawning Processes
Exec'ing Processes Exec'ing Processes
Signals Signals

View File

@ -1,5 +1,5 @@
// Writing a basic HTTP server is easy using the // Написание базового HTTP сервера очень легкореализуемо
// `net/http` package. // с пакетом `net/http`.
package main package main
import ( import (
@ -7,26 +7,27 @@ import (
"net/http" "net/http"
) )
// A fundamental concept in `net/http` servers is // Фундаментальная концепция серверов `net/http` - это
// *handlers*. A handler is an object implementing the // *обработчики*. Обработчик - это объект, реализующий
// `http.Handler` interface. A common way to write // интерфейс `http.Handler`. Распространенным способом
// a handler is by using the `http.HandlerFunc` adapter // написания обработчика является использование адаптера
// on functions with the appropriate signature. // `http.HandlerFunc` для функций с соответствующей
// подписью.
func hello(w http.ResponseWriter, req *http.Request) { func hello(w http.ResponseWriter, req *http.Request) {
// Functions serving as handlers take a // Функции, выполняющие функции обработчиков, принимают
// `http.ResponseWriter` and a `http.Request` as // в качестве аргументов `http.ResponseWriter` и
// arguments. The response writer is used to fill in the // `http.Request`. Response writer используется для
// HTTP response. Here our simple response is just // наполнения HTTP-ответа. Здесь наш простой ответ
// "hello\n". // "hello\n".
fmt.Fprintf(w, "hello\n") fmt.Fprintf(w, "hello\n")
} }
func headers(w http.ResponseWriter, req *http.Request) { func headers(w http.ResponseWriter, req *http.Request) {
// This handler does something a little more // Этот обработчик делает что-то более сложное,
// sophisticated by reading all the HTTP request // читая все заголовки HTTP-запроса и вставляя их в
// headers and echoing them into the response body. // тело ответа.
for name, headers := range req.Header { for name, headers := range req.Header {
for _, h := range headers { for _, h := range headers {
fmt.Fprintf(w, "%v: %v\n", name, h) fmt.Fprintf(w, "%v: %v\n", name, h)
@ -36,15 +37,15 @@ func headers(w http.ResponseWriter, req *http.Request) {
func main() { func main() {
// We register our handlers on server routes using the // Мы регистрируем наши обработчики на сервере,
// `http.HandleFunc` convenience function. It sets up // используя удобную функцию `http.HandleFunc`. Она
// the *default router* in the `net/http` package and // устанавливает *маршрут по умолчанию* в пакете
// takes a function as an argument. // `net/http` и принимает функцию в качестве аргумента.
http.HandleFunc("/hello", hello) http.HandleFunc("/hello", hello)
http.HandleFunc("/headers", headers) http.HandleFunc("/headers", headers)
// Finally, we call the `ListenAndServe` with the port // Наконец, мы вызываем `ListenAndServe` с портом и
// and a handler. `nil` tells it to use the default // обработчиком. nil говорит использовать только что
// router we've just set up. // настроенный маршрутизатор по умолчанию.
http.ListenAndServe(":8090", nil) http.ListenAndServe(":8090", nil)
} }

View File

@ -1,6 +1,6 @@
# Run the server in the background. # Запускаем сервер в фоне.
$ go run http-servers.go & $ go run http-servers.go &
# Access the `/hello` route. # Делаем запрос по адресу `/hello`.
$ curl localhost:8090/hello $ curl localhost:8090/hello
hello hello