说明

介绍如何快速搭建一个http服务

目录结构

  1. demo/
  2. ├── cmd
  3. ├── handler
  4. └── user.go
  5. └── main.go
  6. └── conf
  7. └── app.yaml

配置

  • conf/app.yaml
    1. http:
    2. port: 8085

Demo

  • cmd/handler/user.go

    1. package handler
    2. type UserHandler interface{
    3. Register(ctx *gin.Context)
    4. }
    5. // userHandlerImpl UserHandler的实现
    6. type userHandlerImpl struct{}
    7. // Register 注册
    8. func (impl userHandlerImpl) Register(ctx *gin.Context) {
    9. // .. 注册用户的逻辑
    10. response.WrapContext.Success(nil)
    11. }
    12. // NewUserHandler
    13. func NewUserHandler() UserHandler{
    14. return &userHandlerImpl{}
    15. }
    16. // Inject 注入容器
    17. func Inject(container *dig.Container) {
    18. _ = container.Provide(NewUserHandler)
    19. }
  • cmd/main.go

    1. package main
    2. import (
    3. "github.com/ebar-go/ego"
    4. "github.com/ebar-go/ego/http/response"
    5. "github.com/gin-gonic/gin"
    6. "demo/handler"
    7. )
    8. func main() {
    9. app := ego.App()
    10. // 注入handler
    11. handler.Inject(app.Container())
    12. // 加载路由
    13. if err := app.LoadRouter(func (router *gin.Engine, userHandler handler.UserHandler) {
    14. router.GET("/", func(ctx *gin.Context) {
    15. response.WrapContext(ctx).Success(nil)
    16. })
    17. router.POST("/user/register", userHandler.Register)
    18. }); err != nil {
    19. log.Fatalf("load router failed: %v\n", err)
    20. }
    21. // 启动http服务
    22. app.ServeHTTP()
    23. // 启动应用
    24. app.Run()
    25. }

启动

  1. cd demo
  2. go run cmd/main.go

启动后访问:http://localhost:8085/,输出结果如下:

  1. {
  2. "code": 0,
  3. "message": "success",
  4. "data": null,
  5. "meta": {
  6. "trace": {
  7. "trace_id": "trace:eea596a4-ef3c-46ea-90db-2c20e56fc725",
  8. "request_id": "request:2d892e13-1ab1-4b16-8d55-4284cf38ff4f"
  9. },
  10. "pagination": null
  11. }
  12. }