github.com/annchain/OG@v0.0.9/rpc/server.go (about)

     1  // Copyright © 2019 Annchain Authors <EMAIL ADDRESS>
     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  package rpc
    15  
    16  import (
    17  	"context"
    18  	"fmt"
    19  	"github.com/annchain/OG/arefactor/common/goroutine"
    20  	"github.com/gin-gonic/gin"
    21  	"github.com/sirupsen/logrus"
    22  	"net/http"
    23  	"time"
    24  )
    25  
    26  const ShutdownTimeoutSeconds = 5
    27  
    28  type RpcServer struct {
    29  	router *gin.Engine
    30  	server *http.Server
    31  	port   string
    32  	C      *RpcController
    33  }
    34  
    35  func NewRpcServer(port string) *RpcServer {
    36  	c := RpcController{}
    37  	router := c.NewRouter()
    38  	server := &http.Server{
    39  		Addr:    ":" + port,
    40  		Handler: router,
    41  	}
    42  
    43  	rpc := &RpcServer{
    44  		port:   port,
    45  		router: router,
    46  		server: server,
    47  		C:      &c,
    48  	}
    49  	return rpc
    50  }
    51  
    52  func (srv *RpcServer) Start() {
    53  	logrus.Infof("listening Http on %s", srv.port)
    54  	goroutine.New(func() {
    55  		// service connections
    56  		if err := srv.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
    57  			logrus.WithError(err).Fatalf("error in Http server")
    58  		}
    59  	})
    60  }
    61  
    62  func (srv *RpcServer) Stop() {
    63  	ctx, cancel := context.WithTimeout(context.Background(), ShutdownTimeoutSeconds*time.Second)
    64  	defer cancel()
    65  	if err := srv.server.Shutdown(ctx); err != nil {
    66  		logrus.WithError(err).Error("error while shutting down the Http server")
    67  	}
    68  	logrus.Infof("http server Stopped")
    69  }
    70  
    71  func (srv *RpcServer) Name() string {
    72  	return fmt.Sprintf("rpcServer at port %s", srv.port)
    73  }