github.com/erda-project/erda-infra@v1.0.9/providers/legacy/httpendpoints/provider.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package httpendpoints
    16  
    17  import (
    18  	"net/http"
    19  	"reflect"
    20  	"time"
    21  
    22  	"github.com/erda-project/erda-infra/base/logs"
    23  	"github.com/erda-project/erda-infra/base/servicehub"
    24  	"github.com/erda-project/erda-infra/providers/i18n"
    25  	"github.com/gorilla/mux"
    26  )
    27  
    28  // config .
    29  type config struct {
    30  	Addr string `file:"addr" default:":8090" desc:"http address to listen"`
    31  }
    32  
    33  var _ Interface = (*provider)(nil)
    34  
    35  type provider struct {
    36  	C      *config
    37  	L      logs.Logger
    38  	router *mux.Router
    39  	srv    *http.Server
    40  	t      i18n.Translator
    41  }
    42  
    43  // Init .
    44  func (p *provider) Init(ctx servicehub.Context) error {
    45  	i := ctx.Service("i18n").(i18n.I18n)
    46  	p.t = i.Translator("httpendpoints")
    47  	p.srv = &http.Server{
    48  		Addr:              p.C.Addr,
    49  		Handler:           p.router,
    50  		ReadTimeout:       60 * time.Second,
    51  		WriteTimeout:      60 * time.Second,
    52  		ReadHeaderTimeout: 60 * time.Second,
    53  	}
    54  	return nil
    55  }
    56  
    57  // Start .
    58  func (p *provider) Start() error {
    59  	p.L.Infof("starting endpoints at %s", p.C.Addr)
    60  	return p.srv.ListenAndServe()
    61  }
    62  
    63  func (p *provider) Router() *mux.Router { return p.router }
    64  
    65  // Close .
    66  func (p *provider) Close() error {
    67  	return p.srv.Close()
    68  }
    69  
    70  func init() {
    71  	servicehub.Register("http-endpoints", &servicehub.Spec{
    72  		Services:     []string{"http-endpoints"},
    73  		Types:        []reflect.Type{reflect.TypeOf((*Interface)(nil)).Elem()},
    74  		Dependencies: []string{"i18n"},
    75  		Description:  "http endpoints",
    76  		ConfigFunc:   func() interface{} { return &config{} },
    77  		Creator: func() servicehub.Provider {
    78  			return &provider{
    79  				router: mux.NewRouter(),
    80  			}
    81  		},
    82  	})
    83  }