基于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 的同目录下放入图片、文件等资源, 当做一个文件服务器,在局域网供其他人下载。