实战Go web Hello world项目

实战Go web Hello world项目

该项目有什么特性

  • 规范了http响应
  • 每层都有标准的接口
  • 路由与控制分离
  • 提供简洁的启动方法

技术栈

  • go环境
  • mysql
  • gin 提供web化服务
  • go mod 提供包管理

工程结构

在这里插入图片描述

响应输出

在这里插入图片描述

代码结构分析

  • 包结构分析

    • com.cn
      dao : 提供数据库层操作
      model: 提示实体类
      service: 业务处理类
      web: 提供web服务类
      router: 提供路由服务
      GoWebApplication: 该类为服务启动类
  • 业务层分析

web 层处理:

该层主要是对响应做统一处理.
BaseResponse
// TODO 这个地方后期需要调整为类似于java中的泛型

      type BaseResponse struct {
        	Code int `json:"code"`
        	Message string `json:"message"`
        	Data []User `json:"data"`
        }
  • 定义标准模板
   type BaseApi interface {
   	/**
   	  添加接口Add
   	 */
   	Add(user com_cn_model.User) com_cn_model.BaseResponse
   	/**
   	  删除接口Delete
   	*/
   	Delete(id int) com_cn_model.BaseResponse
   	/**
   	  更新接口Update
   	*/
   	Update(user com_cn_model.User) com_cn_model.BaseResponse
   	/**
   	  更新接口Update
   	*/
   	Get(user com_cn_model.User) com_cn_model.BaseResponse
   	/**
   	分页接口List
   	*/
   	List(user com_cn_model.User , pageSize int, pageNum int) com_cn_model.BaseResponse
   }   

如果添加也是只需要实现该接口就行

  • service层
    该层主要是对业务进行处理对逻辑做判断

  • model 定义实体类对象

     type User struct {
      Id int  `json:"id"`// 用户的唯一标识
      Name string  `json:"name"`// 用户的名字
      Age string  `json:"age"`// 用户年龄
     }
    
  • dao层 对数据库层操作
    1、获取链接啊
    2、 操作数据库等操作

  • router 提供http服务 使用的gin

    • 定义标准接口
    • 对路由接口进行分组
    • 对外提供http服务
type AppRouter struct {
	AppRouterRun
}

type AppRouterRun interface {

	/**
	 	定义启动接口
	 */
	Run()
}

func (c AppRouter) Run(){
	r := gin.Default()
	// 
	group := r.Group("/user")
	group.GET("/get", UserRouterImpl{}.Get)
	r.Run("127.0.0.1:8080")
}

在spring中你可以理解冲RequestMapping用于窄化请求,r.Group("/user") 跟他的意思类似。

  • GoWebApplication
    该类为总个服务的入口
import (
	router "goweb/com.cn.router"
)

/**
   应用的入口函数
*/
func  main()  {
	router.AppRouter{}.Run()
}

为什么我要提供一个类做为主要启动的类呢,因为springboot也是提供一个main启动,虽然没有springboot的一些特性自动装配等等。但是提供一个main启动类,这样看上去代码整洁。

后期改进的地方

  • 提供类似于spring容器一样的工具,这样就不需要复杂的操作,同时也会提供代码的可扩展性
  • 提供类似mybatis数据库表自动转换为实体类对象

猜你喜欢

转载自blog.csdn.net/qq_30561643/article/details/105707154