基於python和golang的輕量級http服務器的搭建

 閱讀大約需要1分鐘

在移動應用程序開發中,有時候需要測試傳遞到服務器的參數的正確性,這時候可以自己搭建輕量級服務器來解決。

1.python簡易服務器搭建

在Python中有很多好用的庫,今天給大家介紹的就是sanic。

sanic是一款用python3.5+寫的web framework,用法和flask類似,sanic的特點是非常快。

sanic安裝非常簡單 在終端中輸入pip3 install sanic 即可安裝

之後就可以用sanic來開發程序了,代碼如下:

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)

以上代碼即可完成一個簡易的python web服務器搭建。

2.golang簡易服務器搭建

新建文件http.go,輸入以下代碼:

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)
}

編譯go build hello.go

執行./hello即完成了簡易的web服務器搭建,之後可以在可執行文件 hello 的同目錄下放入圖片、文件等資源, 當做一個文件服務器,在局域網供其他人下載。