Hello world of go web programming

Time:2020-3-11

Summary

Plan to write a series on go web programming. Starting from the preparation of go web program based on net / HTTP package, this paper introduces the basic knowledge of processor, request, response and so on. Then go to the use of the framework. Some source code analysis will be interspersed in the middle. Finally, make a practical project.

At present, the go community has a lot of libraries or frameworks for web development. Big and all have beego, level. The super high performance ones are echo, fasthttp, gin (at present, GitHub has the most stars). There are many others that focus on a specific aspect, most of them belong to routing, for example: MUX / httprouter.

So why start with the original net / HTTP package? Because most of these libraries / frameworks are based on net / HTTP packages, which provide easy-to-use functions, such as routing parameters(/:name/:age)/Routing grouping, etc. Mastering the basic knowledge and net / HTTP, learning other frameworks is bound to work twice as well. Whether you are quick to use libraries and frameworks, or in-depth reading of the source code, you can be handy.

HTTP

HTTP protocol is the cornerstone of the whole Internet. People in technology, products, operations and even non internet industries deal with HTTP protocol every day. We use HTTP every day when we browse the web. Now many apps also use HTTP internally to interact with the server. So to learn web programming, HTTP protocol must be mastered.

HTTP is a stateless, text-based protocol. It is flexible, stable and powerful. Only a few revisions have been made since it was issued in 1991. Here is a brief history of HTTP development:

  • In 1991, the first version of HTTP, 0.9, was created by Tim Berners Lee. At first, there was only one method get, and it was stipulated that the server could only return data in HTML format.
  • In 1996, HTTP 1.0 was released, supporting post and head methods.
  • In 1999, HTTP 1.1 was released, adding five methods: put / delete / options / trace / connect,And allow developers to add more methods themselves
  • In 2015, HTTP 2.0 was released, and many modifications were made to improve the performance, such as binary format, full multiplexing.

HTTP is a request response protocol. All operations begin with one request and end with one response.

HTTP request

The format of the HTTP request is very simple. A request consists of the following four parts:

  • Request line;
  • Zero or more headers;
  • A blank line;
  • An optional message body.

The first important part is the request line, which has the following format:

Method Path Version
  • Method: the requested method that represents the operation on the resource. Common methods areGET/POST/PUT/DELETE
  • Path: the path of the requested resource, such as/user/info.html
  • Version: the version number of HTTP, written in version 1.1HTTP/1.1

The second part is the first part of the request, each of which occupies a row. First used by colon(:)Separated key value pairs, such asContent-Type: x-www-form-urlencoded

The third part is a blank line. Be careful,Even if there is no first part, the blank lines after cannot be omitted

Finally, it is an optional message body. If there is a principal, the server willContent-TypeThe specified format to parse this part of the content.

HTTP response

The format of the HTTP response is very similar to the request. A response consists of four parts:

  • Response line;
  • Zero or more headers;
  • A blank line;
  • An optional message body.

The format of the response line is:

StatusCode Description
  • StatusCode: status code, indicating the request status;
  • Description: a short description of the status code.

The first part of the response is the same as the principal part and the request part, which is not mentioned here.

Here is a brief introduction to the status code. HTTP divides status codes into five categories,1XX/2XX/3XX/4XX/5XX

  • 1XXIntelligence status code, also known as information status code. Through such status codes, the server informs the client that it has received the request sent by the client. Several common status codes are as follows:

    • 100 Continue: indicates that the content received by the server so far is normal, and the client should continue to request. If completed, ignore it.
    • 101 Switching Protocol: this status code is in response to the clientUpgradeThe protocol sent first and indicating that the server is also switching. If the client requests to switch the protocol, the server will switch the protocol to websocket and send the status code to the clientUpgradeFill in websocket in the first part.
  • 2XX: success status code. Indicates that the server has received the request from the client and successfully processed the request. Several common status codes are as follows:

    • 200 OK: This is the most common status code, indicating that the request is successful.
    • 201 Created: the request succeeded and a new resource was created as a result.
  • 3XX: redirect status code. The server received the request, but in order to process the request completely, the client needs to perform the specified action. Generally used for URL redirection. Several common status codes are as follows:

    • 300 Multiple Choice: the requested resource has a series of optional feedback information, each with its own specific address. Users or browsers can choose an address for redirection.
    • 302 Moved Permanently: the requested resource has been permanently moved to a new location.
  • 4XX: client error status code. Indicates that there is an error in the request sent by the client, for example, the format is incorrect. Common status codes are as follows:

    • 404 Not Found: the most common status code, indicating that the page does not exist.
    • 405 Method Not Allowed: the requested method is not allowed.
  • 5XX: server error status code. Indicates that the server could not process the request properly for some reason. Common status codes are as follows:

    • 500 Internal Server Error: the server encountered a situation where it did not know how to handle it.
    • 501 Not Implemented: this request method is not supported by the server.

First go web program

Talk is cheap, show me the Code!

Next, let’s write a web version of the “Hello world” program. We will use the net / HTTP package provided by go language. The function of the package is very powerful, and it is very convenient to use.

  • First, in$GOPATHCreate a project directory under the directorygo-web-example
  • staygo-web-exampleCreate a1-hello_worldProgram directory;
  • Establishserver.goFile, enter the following:
package main

import (
    "fmt"
    "log"
    "net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello World")
}

func main() {
    http.HandleFunc("/", hello)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        log.Fatal(err)
    }
}
  • Open command line, enter$GOPATH/go-web-example/1-hello_worldDirectory, enter command:go run server.go, our first server program ran.

Hello world of go web programming

  • Open the browser and enter the web addresslocalhost:8080“Hello, world” is displayed on the web page!

Hello world of go web programming

Let’s parse the program.

http.HandleFunctakehelloFunction register to root/Up,helloFunctions are also called processors. It takes two parameters, the first of which is a type ofhttp.ResponseWriterThe response is sent to the client through it. The second parameter is a type ofhttp.RequestThe structure pointer and the information sent by the client can be obtained through this structure.

Then?http.ListenAndServeThe request will be monitored on port 8080 and then submitted to thehelloHandle.

Because the net / HTTP package encapsulates many details for us, our use is so simple.

summary

This paper briefly introduces the development history of HTTP, the format of HTTP request and response, and writes the first go web program. As the cornerstone of the whole Internet, the importance of HTTP protocol can not be overemphasized. It is a knowledge that every developer must master. Net / HTTP of go language encapsulates many details for the development of web program. Using it to develop web programs is very simple. Finally, in order to deepen the impression of learning, I drew a brain map. It is expected to form a complete knowledge system after learning.

Hello world of go web programming

Next, let’s learn more about HTTP requests.

Reference material

  1. Go web programming
  2. HTTP response code

I

My blog

Welcome to my WeChat official account, GoUpUp, learn together and make progress together.

Hello world of go web programming

Recommended Today

Build HTTP service with C + + Mongoose

Mongoose source code address:https://github.com/cesanta/mo… Mongoose user manual:https://www.cesanta.com/devel… Mngoose set up HTTP service #include <string> #include “mongoose.h” using namespace std; static const char *s_http_port = “8000”; static void ev_handler(mg_connection *nc, int ev, void *ev_data) { struct http_message *hm = (struct http_message *) ev_data; if (ev == MG_EV_HTTP_REQUEST) { std::string uri; if (hm->uri.p && hm->uri.p[0] == ‘/’) […]