当前位置: 首页 > 工具软件 > TarsGo > 使用案例 >

TarsGo本地服务运行

曾嘉福
2023-12-01

记录一下自己犯的愚蠢的坑,按照官网提供的写了个http demo,然后怎么运行都不对,查看了一下源码,仅仅是因为命令行传入的格式不对。

配置文件在根目录下,文件名为默认的 config.conf

main函数:

func main() {
	cfg := tars.GetServerConfig()
	if cfg == nil {
		return
	}
	mux := &tars.TarsHttpMux{}
	mux.HandleFunc("/", handler.HandlerExample)
	tars.AddHttpServant(mux, cfg.App+"."+cfg.Server+".GoWebObj")
	tars.Run()
}

HandlerExample函数(放在了handler包里了,分离一下主函数和功能函数):

func HandlerExample(resp http.ResponseWriter, req *http.Request) {
	time_fmt := "2006-01-02 15:04:05"
	local_time := time.Now().Local()
	time_str := local_time.Format(time_fmt)
	ret_str := fmt.Sprintf("{\"msg\":\"Hello, Tars-Go!\", \"time\":\"%s\"}", time_str)
	value := req.URL.Query()
	fmt.Println(value.Get("hello"))
	resp.Header().Set("Content-Type", "application/json;charset=utf-8")
	resp.Write([]byte(ret_str))
}

接下来就是编译,在根目录下执行: go build main.go

然后生成可执行文件:main

然后本地运行:./main -config=config.conf

如果是vscode配置一下Lanch.json就行了

刚刚从c++转go,慢慢适应语法,go看源码很方便相对C++来说简单很多。

 类似资料: