快速开始
目标¶
我们计划开发一个极简web页面,每隔1s,从后端接口获取服务器的最新时间并显示在页面上。
完成这些,只需要少量代码即可。
前提¶
您已经按前一章节的内容,下载了ie310go的源码,并确保源码目录是:
{yourGoPath}/src/github.com/ie310mu
创建项目¶
创建目录:{yourGoPath}/src/i3go_t001,并将刚才下载的两个文件jquery.min.js、base.js放进去备用。
动态接口¶
在i3go_t001目录下,创建文件main.go,并输入以下代码:
package main import ( "time" "github.com/ie310mu/ie310go" "github.com/ie310mu/ie310go/common/convert" "github.com/ie310mu/ie310go/common/dir" "github.com/ie310mu/ie310go/route" ) func main() { httpConfig := route.ServerHTTPConfig{Port: "8103", ServiceSuffix: "goss", Jsonp: true, ServeStaticFunc: route.DefaultServeStatic, DefaultStaticDir: dir.GetCurrentPath()} srv := route.NewServerHTTP(httpConfig, "httpServer") srv.RegisterService(&TimeService{}) route.RegisterServer(srv) ie310go.Run(nil) } //TimeService .. type TimeService struct { route.BaseService } //GetServerTime .. func (s TimeService) GetServerTime(args *route.ServiceArgs) string { now := time.Now() str := convert.DateTimeWithSecToStr(now) return str }
静态网页文件¶
在i3go_t001目录下,创建文件index.html,并输入以下代码:
<!DOCTYPE html> <html> <head></head> <body> <div id="serverTime"></div> <script src="/jquery.min.js"></script> <script src="/base.js"></script> <script> getServerTime(); function getServerTime() { beginInvokeJsonService("timeService.goss", "getServerTime", {}, function (e) { $("#serverTime").html(e.data); setTimeout(function () { getServerTime(); }, 1000); }, invokeServiceError); } </script> </body> </html>
下载示例代码¶
启动¶
在i3go_t001目录下执行命令:(注意不要使用go run main.go,因为那样运行目录是一个临时目录,会访问不到网页文件)
go build main.go main