Web 的基本功能如下:
使用 Node 的 Express, Python 的 Flask, Go 的 Gin 等 Web 框架实现 Web 的基本功能。
# Node Express
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| const express = require('express') const app = express()
app.use(express.urlencoded({ extended: false })) app.use(express.json())
app.use('/static', express.static('static'))
app.get('/', function(req, res) { console.log(req.headers.a) res.header('b', 'c') res.send('hello express') })
app.get('/path/:id', function(req, res) { console.log(req.params.id) res.send(req.params.id) })
app.get('/querystring', function(req, res) { console.log(req.query) res.send(req.query.username) })
app.post('/form', function(req, res) { console.log(req.body) res.send(req.body.username) })
app.post('/json', function(req, res) { console.log(req.body) res.json({ a: 12, b: 'bb' }) }) app.listen(3001)
|
# Python Flask
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| from flask import Flask,request import json
app = Flask(__name__)
@app.route('/path/<id>') def f1(id): return id
@app.route('/querystring') def f2(): a = request.args.to_dict().get("a") return a
@app.route('/form',methods=['post']) def f3(): b = request.form.to_dict().get("b") return b
@app.route('/json',methods=['post']) def f4(): jsonstr = request.data.decode('utf-8') c = json.loads(jsonstr).get("c") return str(c)
@app.route('/') def hello(): print(request.headers.get('a')) return {'a':11,'b':'bb'},200,{"f":"g"}
if __name__ == '__main__': app.debug = True app.run(host='0.0.0.0', port=3002)
|
# Go Gin
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| package main
import "github.com/gin-gonic/gin" import "fmt"
func main() { r := gin.Default() r.Static("/static","./static")
r.GET("/", func(c *gin.Context) { fmt.Println(c.GetHeader("a")) c.Header("k","l") c.String(200,"hello gin") })
r.GET("/path/:id",func(c *gin.Context) { c.String(200,c.Param("id")) })
r.GET("/querystring",func(c *gin.Context) { c.String(200,c.Query("username")) })
r.POST("/form",func(c *gin.Context) { c.String(200,c.PostForm("username")) })
r.POST("/json",func(c *gin.Context) { var amap interface{} c.BindJSON(&amap) c.JSON(200,amap) }) r.Run(":3003") }
|