github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/http/onlinedoc/handlerimpl.go (about)

     1  package onlinedoc
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/json"
     6  	"fmt"
     7  	"net/http"
     8  	"text/template"
     9  )
    10  
    11  // Oas store OpenAPI3.0 description json string
    12  var Oas string
    13  
    14  // OnlineDocHandlerImpl define implementation for OnlineDocHandler
    15  type OnlineDocHandlerImpl struct {
    16  }
    17  
    18  // GetOpenAPI return OpenAPI3.0 description json string
    19  func (receiver *OnlineDocHandlerImpl) GetOpenAPI(_writer http.ResponseWriter, _req *http.Request) {
    20  	_writer.Write([]byte(Oas))
    21  }
    22  
    23  // GetDoc return documentation web UI
    24  func (receiver *OnlineDocHandlerImpl) GetDoc(_writer http.ResponseWriter, _req *http.Request) {
    25  	var (
    26  		tpl    *template.Template
    27  		err    error
    28  		buf    bytes.Buffer
    29  		scheme string
    30  	)
    31  	if tpl, err = template.New("onlinedoc.tmpl").Parse(indexTmpl); err != nil {
    32  		panic(err)
    33  	}
    34  	doc, _ := json.Marshal(Oas)
    35  	if _req.TLS == nil {
    36  		scheme = "http"
    37  	} else {
    38  		scheme = "https"
    39  	}
    40  	if err = tpl.Execute(&buf, struct {
    41  		Doc    string
    42  		DocUrl string
    43  	}{
    44  		Doc:    string(doc),
    45  		DocUrl: fmt.Sprintf("%s://%s/go-doudou/openapi.json", scheme, _req.Host),
    46  	}); err != nil {
    47  		panic(err)
    48  	}
    49  	_writer.Header().Set("Content-Type", "text/html; charset=utf-8")
    50  	_writer.Write(buf.Bytes())
    51  }
    52  
    53  // NewOnlineDocHandler creates new instance for OnlineDocHandlerImpl
    54  func NewOnlineDocHandler() OnlineDocHandler {
    55  	return &OnlineDocHandlerImpl{}
    56  }