github.com/Redstoneguy129/cli@v0.0.0-20230211220159-15dca4e91917/test/mocks/docker/server.go (about)

     1  package docker
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"github.com/gin-gonic/gin"
     7  )
     8  
     9  const (
    10  	IDAlphabet = "abcdef0123456789"
    11  	IDLength   = 12
    12  )
    13  
    14  // Server struct with route handlers
    15  type Server struct {
    16  	PingHandler             func(c *gin.Context)
    17  	ContainerInspectHandler func(c *gin.Context)
    18  	ExecCreateHandler       func(c *gin.Context)
    19  	ExecStartHandler        func(c *gin.Context)
    20  }
    21  
    22  var defaultHandler = func(c *gin.Context) {
    23  	c.JSON(http.StatusNotImplemented, gin.H{
    24  		"message": "Not implemented",
    25  	})
    26  }
    27  
    28  // NewServer creates a new server with default handlers
    29  func NewServer() *Server {
    30  	s := Server{
    31  		ExecCreateHandler:       defaultHandler,
    32  		ExecStartHandler:        defaultHandler,
    33  		ContainerInspectHandler: defaultHandler,
    34  	}
    35  	return &s
    36  }
    37  
    38  // NewRouter creating a new router and setting the routes for the server.
    39  func (s *Server) NewRouter() *gin.Engine {
    40  	root := gin.Default()
    41  	root.HEAD("/_ping", s.ping)
    42  	root.GET("/_ping", s.ping)
    43  
    44  	router := root.Group("/v1.41")
    45  
    46  	containers := router.Group("/containers")
    47  	containers.GET("/:id/json", s.inspectContainer)
    48  	containers.POST("/:id/exec", s.createExec)
    49  
    50  	exec := router.Group("/exec")
    51  	exec.POST("/:id/start", s.startExec)
    52  	exec.GET("/:id/json", s.inspectContainer)
    53  
    54  	return root
    55  }
    56  
    57  // ping
    58  func (s *Server) ping(c *gin.Context) {
    59  	if s.PingHandler == nil {
    60  		c.Header("API-Version", "1.41")
    61  		c.Header("OSType", "linux")
    62  		c.Status(http.StatusOK)
    63  	} else {
    64  		s.PingHandler(c)
    65  	}
    66  }
    67  
    68  // container
    69  func (s *Server) inspectContainer(c *gin.Context) {
    70  	if s.ContainerInspectHandler == nil {
    71  		c.JSON(http.StatusInternalServerError, gin.H{
    72  			"message": "handler is nil",
    73  		})
    74  	} else {
    75  		s.ContainerInspectHandler(c)
    76  	}
    77  }
    78  
    79  // exec
    80  func (s *Server) createExec(c *gin.Context) {
    81  	if s.ExecCreateHandler == nil {
    82  		c.JSON(http.StatusInternalServerError, gin.H{
    83  			"message": "handler is nil",
    84  		})
    85  	} else {
    86  		s.ExecCreateHandler(c)
    87  	}
    88  }
    89  
    90  func (s *Server) startExec(c *gin.Context) {
    91  	if s.ExecStartHandler == nil {
    92  		c.JSON(http.StatusInternalServerError, gin.H{
    93  			"message": "handler is nil",
    94  		})
    95  	} else {
    96  		s.ExecStartHandler(c)
    97  	}
    98  }