github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_server_openapi.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package ghttp
     8  
     9  import (
    10  	"context"
    11  
    12  	"github.com/gogf/gf/v2/net/goai"
    13  	"github.com/gogf/gf/v2/text/gstr"
    14  )
    15  
    16  // initOpenApi generates api specification using OpenApiV3 protocol.
    17  func (s *Server) initOpenApi() {
    18  	if s.config.OpenApiPath == "" {
    19  		return
    20  	}
    21  	var (
    22  		ctx     = context.TODO()
    23  		err     error
    24  		methods []string
    25  	)
    26  	for _, item := range s.GetRoutes() {
    27  		switch item.Type {
    28  		case HandlerTypeMiddleware, HandlerTypeHook:
    29  			continue
    30  		}
    31  		if item.Handler.Info.IsStrictRoute {
    32  			methods = []string{item.Method}
    33  			if gstr.Equal(item.Method, defaultMethod) {
    34  				methods = SupportedMethods()
    35  			}
    36  			for _, method := range methods {
    37  				err = s.openapi.Add(goai.AddInput{
    38  					Path:   item.Route,
    39  					Method: method,
    40  					Object: item.Handler.Info.Value.Interface(),
    41  				})
    42  				if err != nil {
    43  					s.Logger().Fatalf(ctx, `%+v`, err)
    44  				}
    45  			}
    46  		}
    47  	}
    48  }
    49  
    50  // openapiSpec is a build-in handler automatic producing for openapi specification json file.
    51  func (s *Server) openapiSpec(r *Request) {
    52  	if s.config.OpenApiPath == "" {
    53  		r.Response.Write(`OpenApi specification file producing is disabled`)
    54  	} else {
    55  		r.Response.WriteJson(s.openapi)
    56  	}
    57  }