github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/gin_app/gin.go (about)

     1  package gin_app
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"time"
     7  
     8  	"github.com/gin-contrib/cors"
     9  	"github.com/gin-gonic/gin"
    10  
    11  	"github.com/johnnyeven/libtools/conf"
    12  	"github.com/johnnyeven/libtools/env"
    13  )
    14  
    15  type GinApp struct {
    16  	Name        string
    17  	IP          string
    18  	Port        int
    19  	SwaggerPath string
    20  	WithCORS    bool
    21  	app         *gin.Engine
    22  }
    23  
    24  func (a GinApp) DockerDefaults() conf.DockerDefaults {
    25  	return conf.DockerDefaults{
    26  		"Port":     80,
    27  		"WithCORS": false,
    28  	}
    29  }
    30  
    31  func (a GinApp) MarshalDefaults(v interface{}) {
    32  	if g, ok := v.(*GinApp); ok {
    33  		if g.Name == "" {
    34  			g.Name = os.Getenv("PROJECT_NAME")
    35  		}
    36  
    37  		if g.SwaggerPath == "" {
    38  			g.SwaggerPath = "./swagger.json"
    39  		}
    40  
    41  		if g.Port == 0 {
    42  			g.Port = 80
    43  		}
    44  	}
    45  }
    46  
    47  func (a *GinApp) Init() {
    48  	if env.IsOnline() {
    49  		gin.SetMode(gin.ReleaseMode)
    50  	}
    51  
    52  	a.app = gin.New()
    53  
    54  	if a.WithCORS {
    55  		a.app.Use(cors.New(cors.Config{
    56  			AllowAllOrigins:  true,
    57  			AllowMethods:     []string{"GET", "POST", "PUT", "HEAD", "DELETE", "PATCH"},
    58  			AllowHeaders:     []string{"Origin", "Content-Length", "Content-Type", "Authorization", "AppToken", "AccessKey"},
    59  			AllowCredentials: false,
    60  			MaxAge:           12 * time.Hour,
    61  		}))
    62  	}
    63  
    64  	a.app.Use(gin.Recovery(), WithServiceName(a.Name), Logger())
    65  }
    66  
    67  type GinEngineFunc func(router *gin.Engine)
    68  
    69  func (a *GinApp) Register(ginEngineFunc GinEngineFunc) {
    70  	ginEngineFunc(a.app)
    71  }
    72  
    73  func (a *GinApp) Start() {
    74  	a.MarshalDefaults(a)
    75  	err := a.app.Run(a.getAddr())
    76  	if err != nil {
    77  		fmt.Fprintf(os.Stderr, "Server run failed[%s]\n", err.Error())
    78  		os.Exit(1)
    79  	}
    80  }
    81  
    82  func (a GinApp) getAddr() string {
    83  	return fmt.Sprintf("%s:%d", a.IP, a.Port)
    84  }