Use go to play the simplest web server ------ By the way, the Content-Type field

web server code s.go:

package main

Import (
    "io"
    "log"
    "net/http"
)

Func handlerHello(w http.ResponseWriter, r *http.Request) {
    io.WriteString(w, "hello girls")
}

Func main() {
    http.HandleFunc("/hello", handlerHello) // Register
    Err := http.ListenAndServe("localhost:8080", nil)
    If err != nil {
        log.Println(err)
    }
}

go run s.go, run up, and then execute http://127.0.0.1:8080/hello in the browser (or send http request with curl on the command line), the result on the browser For:

hello girls

好简单. You can capture the package on the client or server. Very typical http req and rsp.

Let's look at an interesting question. Modify s.go as:

package main

Import (
    "io"
    "log"
    "net/http"
)

Func handlerHello(w http.ResponseWriter, r *http.Request) {
    Str := `
        Table border="1">
        <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
        </tr>
        <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
        </tr>
        </table>
        `

    io.WriteString(w, str)
}

Func main() {
    http.HandleFunc("/hello", handlerHello) // Register
    Err := http.ListenAndServe("localhost:8080", nil)
    If err != nil {
        log.Println(err)
    }
}

Restart the service concurrent request again. The content displayed on the browser is:


        table border="1">
        <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
        </tr>
        <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
        </tr>
        </table>
        

Capture the package and find out: Content-Type: text/plain; charset=utf-8

The browser needs to be displayed according to plain text. Notice that there is one "<" missing on the left side of the above table. After we add it, the code for s.go is as follows:

package main

Import (
    "io"
    "log"
    "net/http"
)

Func handlerHello(w http.ResponseWriter, r *http.Request) {
    Str := `
        <table border="1">
        <tr>
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
        </tr>
        <tr>
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
        </tr>
        </table>
        `

    io.WriteString(w, str)
}

Func main() {
    http.HandleFunc("/hello", handlerHello) // Register
    Err := http.ListenAndServe("localhost:8080", nil)
    If err != nil {
        log.Println(err)
    }
}

Restart the service again, send the request, the browser display is:

row 1, cell 1 row 1, cell 2
row 2, cell 1 row 2, cell 2

抓包看, there is Content-Type: text/html; charset=utf-8

visible, the server will judge The format of str determines the type of Content-Type, which determines how the browser is displayed. The automatic judgment behavior of the server is a bit interesting. In my opinion, this is not very good, you should let the programmer specify Content-Type.

not to say.