Building a lightweight http server based on python and golang

 2 minutes to read

In mobile application development, sometimes it is necessary to test the correctness of the parameters passed to the server. At this time, you can build a lightweight server to solve it.

1. Python simple server construction

There are many useful libraries in Python, and I will introduce you to sanic today.

Sanic is a web framework written in python3.5+, and its usage is similar to flask, but sanic is very fast.

Sanic installation is very simple. Enter pip3 install sanic in the terminal to install

Then you can use sanic to develop the program, the code is as follows:

from sanic import Sanic
from sanic.log import logger
from sanic.response import json

app = Sanic(name="app_server")


@app.route("/")
async def test(request):
    logger.info("request ip is: "+ request.ip)
    logger.info(request.headers)
    return json({"Hello": "World"})


if __name__ == "__main__":
    app.run(port=8080)

The above code can complete a simple python web server construction.

2. Golang simple server construction

Create a new file http.go and enter the following code:

package main

import (
"fmt"
"net/http"
)

func main() {
fmt.Println("Start Server listening on 8080:")
http.Handle("/",http.FileServer(http.Dir("/")))
http.ListenAndServe(":8080",nil)
}

Compile go build hello.go

Execute ./hello to complete the simple web server construction, and then you can put pictures, files and other resources in the same directory as the executable file hello. As a file server, it can be downloaded by others on the local area network.