github.com/linapex/ethereum-go-chinese@v0.0.0-20190316121929-f8b7a73c3fa1/swarm/network/simulation/http.go (about)

     1  
     2  //<developer>
     3  //    <name>linapex 曹一峰</name>
     4  //    <email>linapex@163.com</email>
     5  //    <wx>superexc</wx>
     6  //    <qqgroup>128148617</qqgroup>
     7  //    <url>https://jsq.ink</url>
     8  //    <role>pku engineer</role>
     9  //    <date>2019-03-16 19:16:43</date>
    10  //</624450114387185664>
    11  
    12  
    13  package simulation
    14  
    15  import (
    16  	"fmt"
    17  	"net/http"
    18  
    19  	"github.com/ethereum/go-ethereum/log"
    20  	"github.com/ethereum/go-ethereum/p2p/simulations"
    21  )
    22  
    23  //包默认值。
    24  var (
    25  	DefaultHTTPSimAddr = ":8888"
    26  )
    27  
    28  //WithServer实现用于模拟的生成器模式构造函数
    29  //从HTTP服务器开始
    30  func (s *Simulation) WithServer(addr string) *Simulation {
    31  //如果未提供,则分配默认地址
    32  	if addr == "" {
    33  		addr = DefaultHTTPSimAddr
    34  	}
    35  	log.Info(fmt.Sprintf("Initializing simulation server on %s...", addr))
    36  //初始化HTTP服务器
    37  	s.handler = simulations.NewServer(s.Net)
    38  	s.runC = make(chan struct{})
    39  //向HTTP服务器添加特定于Swarm的路由
    40  	s.addSimulationRoutes()
    41  	s.httpSrv = &http.Server{
    42  		Addr:    addr,
    43  		Handler: s.handler,
    44  	}
    45  	go func() {
    46  		err := s.httpSrv.ListenAndServe()
    47  		if err != nil {
    48  			log.Error("Error starting the HTTP server", "error", err)
    49  		}
    50  	}()
    51  	return s
    52  }
    53  
    54  //注册其他HTTP路由
    55  func (s *Simulation) addSimulationRoutes() {
    56  	s.handler.POST("/runsim", s.RunSimulation)
    57  }
    58  
    59  //运行模拟是实际的端点后运行程序
    60  func (s *Simulation) RunSimulation(w http.ResponseWriter, req *http.Request) {
    61  	log.Debug("RunSimulation endpoint running")
    62  	s.runC <- struct{}{}
    63  	w.WriteHeader(http.StatusOK)
    64  }
    65