Skip to content

kiyonlin/fiblar-demo

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fiber+angular开发web

fiber是最近出道的一款基于fasthttpweb框架。

Fiber is an Express inspired web framework build on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development with zero memory allocation and performance in mind.

我们可以用fiber快速开发api接口,再配合angular实现一个web项目。

环境:macos 10.15.4 + go 1.14.1 + fiber 1.11.1 + angular 9.1.6

新建项目

我们创建一个新的目录叫fiblar-demo

md fiblar-demo && cd fiblar-demo

再使用go mod初始化项目:

go mod init github.com/kiyonlin/fiblar-demo

新建一个main.go文件,内容如下:

package main

import (
	"github.com/gofiber/fiber"
	"log"
)

func main() {
	// Create new Fiber instance
	app := fiber.New()

	// serve Single Page application on "/public"
	// assume static file at dist folder
	app.Static("/", "public")

    // intercept api routes
	apiGroup := app.Group("/api")
	{
		apiGroup.Get("/user", func(c *fiber.Ctx) {
			c.JSON(fiber.Map{"id": 1, "name": "kiyon"})
		})
	}
    
    // other routes just return `public/index.html`, angular will handle them
	app.Get("/*", func(c *fiber.Ctx) {
		if err := c.SendFile("public/index.html"); err != nil {
			c.Next(fiber.ErrInternalServerError)
		}
	})

	// Start server on http://localhost:3000
	log.Fatal(app.Listen(3000))
}

创建新的angular项目

使用angular-cli创建一个新的angular项目:

ng new web

编辑web/angular.json

{
  "other-configs": {},
  "build": {
    "builder": "@angular-devkit/build-angular:browser",
    "options": {
      "outputPath": "../public"
    }
  }
}

这样就可以把编译后的angular项目输出到跟web同一级的public目录,上述基于fiber的程序会读取public目录下的文件。

接下来我们给web/src/app/app.component.ts加一下api请求:

// ...
export class AppComponent {
  title = 'web';

  user: any;

  constructor(private http: HttpClient) {
    this.http.get('/api/user').subscribe(data => this.user = data);
  }
}

这样进入首页后就会触发/api/user的请求,我们把获取到的user展示到页面web/src/app/app.component.html上:

  <!-- ... -->
  <!-- Resources -->
  <h1>User</h1>
  <p>{{user | json}}</p>
  <h2>Resources</h2>
  <p>Here are some links to help you get started:</p>
  <!-- ... -->

再在web/package.json中添加一个脚本,供开发时使用:

{
  "scripts": {
    "build": "ng build --prod",
    "build:watch": "ng build --watch"
  }
}

运行项目

我们使用air在开发过程中热更新服务,按照文档安装即可,以下是.air.conf的核心内容:

root = "."
tmp_dir = "tmp"
[build]
cmd = "go build -o ./tmp/main ./main.go"
bin = "tmp/main"
include_ext = ["go", "toml"]
exclude_dir = ["assets", "tmp", "vendor", "web"]

最后,我们执行air监听后端项目,执行cd web && yarn run build:watch监听前端项目,访问localhost:3000查看结果: demo

总结

本文展示了综合fiberangular开发web项目的一个小例子,权当抛砖引玉,有兴趣的同学可以继续深入研究。最后,我们稍微做下总结:

  • 通过fiber的静态文件服务,我们可以直接提供angular输出的html页面
  • 服务端拦截api路由,前端调用接口时,加上api前缀即可,无跨域问题,其他路由交给angular处理

完整demo,以上。

About

demo for web develop based on fiber and angular

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages