V语言web开发初体验

  V语言中文网  |   2693 |    2019-08-02 14:32:40

近期V语言发布了用于web开发的模块vweb,可以在V语言源码v/vlib/vweb中看到源码。目前vweb还处于demo阶段,相对简陋,可以看到源码中对Response、路由等还尚未实现。


既然是V语言web初体验,那话不多说,现在就码个vweb版"Hello World"吧!

新建一个web.v的文件,代码如下:

module main
import (
    vweb
)
 
const (
    Port = 8080 // 端口号
)
// 定义一个继承vweb.Context的结构体
struct App {
pub mut:
        vweb vweb.Context 
}
 
// 重写init方法,该方法会在每次接收到http请求后调用
pub fn (app mut App) init(){
    println('web init')
}
 
// index 作为访问路由 http://localhost:8080/index
pub fn (app mut App) index(){
    method:=app.vweb.req.method
    println('===method:$method')
    match method{
        'GET' => app.vweb.text('Hello world from get request')
        'POST' => app.vweb.json('{"msg":"Hello world from post request"}')
        else => app.vweb.text('Hello world from other request:$method')
    }
}
 
fn main(){
    println('Running vweb on http://localhost:$Port')
    vweb.run<App>(Port)
}

编译:v -prod web.v

运行: ./web

经过测试,当前的vweb模块在处理404问题上有bug,没有及时关掉链接,导致404之后的请求会异常。作者也在积极改进与完善vweb模块的功能,后续期待吧!

以上代码如果有同学测试需要问题或者有疑惑的地方,可以留言或者加Q群讨论。


登陆后可发表评论


热门评论

暂无评论


最新评论

暂无评论