01 . Go之Gin+Vue開發一個線上外賣應用


項目介紹

我們將開始使用Gin框架開發一個api項目,我們起名為:雲餐廳。如同餓了么,美團外賣等生活服務類應用一樣,雲餐廳是一個線上的外賣應用,應用的用戶可以在線瀏覽商家,商品並下單。

該項目分為客戶端和服務端兩端程序。

  • 1、客戶端程序通過接口從服務端獲取數據,獲取結果后展示數據。
  • 2、服務端程序提供接口Api的訪問功能,執行數據庫操作,並組織數據返回。

客戶端介紹

雲餐廳客戶端使用Vue、ES6、Webpack等技術進行開發,項目開發需要具備前端開發技能,我們聚焦於后端Api功能的開發。

環境准備

運行vue等技術開發的客戶端項目,需要安裝Node.js環境

下載

可以到nodejs的下載頁面: http://nodejs.cn/download/下載對應的安裝包

1.Windows電腦安裝Nodejs環境

  • 1、windows環境下選擇.msi安裝文件。然后進行雙擊node.msi,選擇安裝路徑。
  • 2、配置環境變量。在計算機(或者我的電腦)右擊屬性 -> 高級系統設置 -> 環境變量進行配置。新建NODE_PATH變量並設置Nodejs的安裝目錄。

macOS系統安裝Nodejs

在終端中使用brew命令安裝nodejs。詳細命令:

brew install nodejs

Linux系統安裝Nodejs

在nodejs的下載頁面選擇linux類別下的64位文件,下載文件為tar.xz格式的壓縮文件。然后依次執行解壓縮和建立軟連接的命令:

tar -xvf   node-v10.15.3-linux-x64.tar.xz
vi /etc/profile
export NODEJS=/opt/node/node-v10.15.3-linux-x64
export PATH=$NODEJS/bin:$PATH

// 保存/etc/profile文件后
node -v 
// 看版本
安裝nvm

管理node版本,非必須

// mac
git clone https://github.com/nvm-sh/nvm.git
cd nvm
./install.sh

cat ~/.bash_profile 
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

// 換源
export NVM_NODEJS_ORG_MIRROR=http://npm.taobao.org/mirrors/node
export NVM_IOJS_ORG_MIRROR=http://npm.taobao.org/mirrors/iojs

source ~/.bash_profile 
nvm --version
0.37.0

// 安裝指定版本
nvm install 10.14.2
安裝yarn

包管理工具

brew install yarn
安裝vue cli
npm config set registry https://registry.npm.taobao.org/
npm install -g @vue/cli


yarn global add @vue/cli
創建vue項目
vue create ginessentail-vue
Vue CLI v4.5.8
? Please pick a preset: (Use arrow keys)
  Default ([Vue 2] babel, eslint) 
  Default (Vue 3 Preview) ([Vue 3] babel, eslint) 
❯  Manually select features 




Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: 
 ◉ Choose Vue version
 ◉ Babel
 ◯ TypeScript
 ◯ Progressive Web App (PWA) Support
 ◉ Router
 ◉ Vuex
❯◯ CSS Pre-processors
 ◉ Linter / Formatter
 ◯ Unit Testing
 ◯ E2E Testing



Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, Lin
ter
? Choose a version of Vue.js that you want to start the project with 2.x
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) (Y/n) y




Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): 
  Sass/SCSS (with dart-sass) 
❯ Sass/SCSS (with node-sass) 
  Less 
  Stylus 


                            
Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: 
  ESLint with error prevention only 
❯ ESLint + Airbnb config 
  ESLint + Standard config 
  ESLint + Prettier 

     
                            
Vue CLI v4.5.8
? Please pick a preset: Manually select features
? Check the features needed for your project: Choose Vue version, Babel, Router, Vuex, CSS
 Pre-processors, Linter
? Choose a version of Vue.js that you want to start the project with 3.x (Preview)
? Use history mode for router? (Requires proper server setup for index fallback in product
ion) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default
): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Airbnb
? Pick additional lint features: Lint on save
? Where do you prefer placing config for Babel, ESLint, etc.? (Use arrow keys)
❯ In dedicated config files 
  In package.json 
      
                            
success Saved lockfile.
✨  Done in 17.00s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.22.10
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...
success Saved lockfile.
✨  Done in 8.86s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project ginessentail-vue.
👉  Get started with the following commands:

 $ cd ginessentail-vue
 $ yarn serve

cd ginessentail-vue 
yarn serve                  

引入bootstrap

yarn add vue bootstrap-vue bootstrap

服務端介紹

我們着重后端項目開發

創建項目

在gopath的src目錄下,創建OnlineRestaurant目錄,作為服務端項目。

mkdir CloudRestaurant
創建配置文件目錄
mkdir config

config目錄中,配置app.json配置文件

{
  "app_name": "youmen",
  "app_mode": "debug",
  "app_host": "localhost",
  "app_port": "8090"
}

創建一個tool目錄

里面創建config.go文件,用於解析項目配置信息,config.go如下

type Config struct {
	AppName  string         `json:"app_name"`
	AppMode  string         `json:"app_mode"`
	AppHost  string         `json:"app_host"`
	AppPort  string         `json:"app_port"`
}
var _cfg *Config = nil
func GetConfig() *Config {
	return _cfg
}

func ParseConfig(path string) (*Config, error) {
	file, err := os.Open(path)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	reader := bufio.NewReader(file)
	decoder := json.NewDecoder(reader)
	if err := decoder.Decode(&_cfg); err != nil {
		return nil, err
	}
	return _cfg, nil
}
編寫main.go
func main() {
    //讀取配置文件
	cfg, err := toolbox.ParseConfig("./config/app.json")
	if err != nil {
		toolbox.Error(err.Error())
		return
	}
	app := gin.Default()
	app.Run(cfg.AppHost + ":" + cfg.AppPort)
}

編寫hello world

編寫Controller: 創建controller,並創建HelloController。

package controller

import "github.com/gin-gonic/gin"

type HelloController struct {
}

func (hello *HelloController) Router(engine *gin.Engine) {
	engine.GET("/hello", hello.Hello)
}

func (hello *HelloController) Hello(context *gin.Context) {
	context.JSON(200, map[string]interface{}{
		"message": "hello world",
	})
}
添加路由

在main.go程序中添加路由設置

func registerRouter(router *gin.Engine) {
     new(controller.HelloController).Router(router)
}

項目前端使用及調試

前端項目目錄說明

本項目的前端項目是使用nodejs的vue框架進行開發而成的。名稱為shop-client。該項目的源碼如下圖所示:

如上圖所示的是shop-client前端項目.對該前端項目框架作如下解釋說明:

  • build:build目錄是指定的項目編譯目錄,該項目的編譯配置相關的操作,都在該目錄中進行配置和指定。
  • config:config目錄主要是對項目全局進行相關的配置,以及測試或者發布版本進行配置。
  • dist:所有的.vue頁面編譯后成為的js文件,都會輸出到該目錄中。
  • node_modules:該目錄是nodejs項目所需要的依賴的第三方庫的代碼目錄。由於該目錄體積較大,在進行項目遷移或者項目拷貝時,可以將該目錄刪除,在項目的根目錄中執行npm install命令會重新生成並下載所需要的第三方的代碼庫。
  • src:該目錄是存放前端工程項目的源碼目錄。
  • static:該目錄用於存放靜態的文件,比如js、css文件等。
  • package.json:執行npm init命令會生成該文件,該文件是node項目的配置文件,其中包含項目的編譯和第三方依賴庫依賴信息等內容。
運行前端項目

安裝好了nodejs環境后,可以使用命令對前端項目進行操作

進入項目中

cd shop-client

常用命令

...
"scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "lint": "eslint --ext .js,.vue src",
    "build": "node build/build.js"
}
...

按照上述的腳本命令配置,可以實現很多指令功能.

比如說,可以使用如下命令運行編譯項目:

npm run build

因為在scripts腳本中配置了start命令,只有start命令可以忽略run,當然,npm start會具體執行的命令是npm run dev, 因此可以通過npm run dev命令來運行項目.

請求接口API

在shop-client前端項目的src目錄下的api目錄中,有兩個js文件,分別為ajax.js文件和index.js文件。

  • ajax.js文件:該文件中封裝了前端項目進行異步網絡請求的方法ajax,該函數包含三個參數,分別是:url、data、type,表示請求路徑,請求參數和請求方法。
  • index.js文件:在該文件中,引入了ajax.js文件和其中的ajax方法,定義了基礎請求路徑BASE_URL常量,此項目中的請求端口為8090,與后台服務器監聽的端口一致。如果想自己修改服務器監聽端口,要記得將前端代碼BASE_URL常量中的端口也要一並修改。另外,在index.js文件中定義了本項目功能開發所需要的接口,供在.vue文件中進行使用。
前端頁面vue源文件

在shop-client前端項目的src目錄下的pages目錄中,存放的是項目的頁面源文件,頁面源文件是.vue為擴展名的文件。

在該項目中,根據項目功能和模塊划分為更詳細的目錄:Login、Msite、Order、Profile、Search、Shop等幾個目錄。

路由文件

在src目錄下存在有router目錄,其中包含一個index.js文件,該文件是前端頁面的路由頁面,通過該頁面的路由配置,進行展示對應的前端頁面的vue源文件。

路由模塊使用到了第三方的路由庫:vue-router。對於第三方vue-router的配置依賴,可以在package.json文件中的dependencies配置模塊中找到:

...
"dependencies": {
    "axios": "^0.18.0",
    "better-scroll": "^1.12.6",
    "date-fns": "^1.29.0",
    "fastclick": "^1.0.6",
    "mint-ui": "^2.2.13",
    "mockjs": "^1.0.1-beta3",
    "swiper": "^4.3.3",
    "vue": "^2.5.2",
    "vue-router": "^3.0.1",
    "vuex": "^3.0.1"
}
...
項目入口

在shop-client項目根目錄下的src目錄中,有兩個代表項目入口的文件,分別是js文件和vue文件。main.js是項目運行的總入口,在main.js文件內部,引入並使用了App.vue文件,同時引入了router路由文件。

App.vue是項目的主頁面的布局,並引入了頁面樣式文件。

項目運行

需要運行前端項目進行調試時,執行以下步驟

/*
		cd shop-client
		npm run dev
*/

然后在瀏覽器中訪問8080端口: http://localhost:8080 可以訪問到前端頁面,如下圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM