github.com/roblesoft/oak@v0.0.0-20230306162712-e6c5c487469e/oak.go (about)

     1  package oak
     2  
     3  import (
     4  	"context"
     5  	"log"
     6  	"net/http"
     7  	"os"
     8  	"os/signal"
     9  	"time"
    10  )
    11  
    12  type Oak struct {
    13  	router *Router
    14  	Server *http.Server
    15  }
    16  
    17  func New() *Oak {
    18  	return &Oak{
    19  		Server: &http.Server{
    20  			Addr: ":3000",
    21  		},
    22  		router: &Router{
    23  			logger: log.New(os.Stdout, "Api: ", log.LstdFlags),
    24  			trees:  nil,
    25  		},
    26  	}
    27  }
    28  
    29  type OakHandle func(ctx *Ctx)
    30  
    31  func (o *Oak) oakHandleToHandlerFunc(handle OakHandle) http.HandlerFunc {
    32  	return func(w http.ResponseWriter, r *http.Request) {
    33  		ctx := &Ctx{
    34  			Context:  context.Background(),
    35  			response: w,
    36  			request:  r,
    37  		}
    38  		handle(ctx)
    39  	}
    40  }
    41  
    42  func (o *Oak) GET(path string, handle OakHandle) {
    43  	handler := o.oakHandleToHandlerFunc(handle)
    44  	o.router.GET(path, handler)
    45  }
    46  
    47  func (o *Oak) POST(path string, handle OakHandle) {
    48  	handler := o.oakHandleToHandlerFunc(handle)
    49  	o.router.POST(path, handler)
    50  }
    51  
    52  func (o *Oak) PATCH(path string, handle OakHandle) {
    53  	handler := o.oakHandleToHandlerFunc(handle)
    54  	o.router.PATCH(path, handler)
    55  }
    56  
    57  func (o *Oak) PUT(path string, handle OakHandle) {
    58  	handler := o.oakHandleToHandlerFunc(handle)
    59  	o.router.PUT(path, handler)
    60  }
    61  
    62  func (o *Oak) DELETE(path string, handle OakHandle) {
    63  	handler := o.oakHandleToHandlerFunc(handle)
    64  	o.router.DELETE(path, handler)
    65  }
    66  
    67  func (o *Oak) HEAD(path string, handle OakHandle) {
    68  	handler := o.oakHandleToHandlerFunc(handle)
    69  	o.router.HEAD(path, handler)
    70  }
    71  
    72  func (o *Oak) OPTIONS(path string, handle OakHandle) {
    73  	handler := o.oakHandleToHandlerFunc(handle)
    74  	o.router.OPTIONS(path, handler)
    75  }
    76  
    77  func (o *Oak) Run() {
    78  	o.Server.Handler = o.router
    79  	go func() {
    80  		err := o.Server.ListenAndServe()
    81  		if err != nil {
    82  			o.router.logger.Fatal(err)
    83  		}
    84  	}()
    85  
    86  	sigChannel := make(chan os.Signal)
    87  	signal.Notify(sigChannel, os.Interrupt)
    88  	signal.Notify(sigChannel, os.Kill)
    89  	sig := <-sigChannel
    90  	o.router.logger.Println("Received terminate, graceful shutdown", sig)
    91  	timeoutContext, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    92  	defer cancel()
    93  	o.Server.Shutdown(timeoutContext)
    94  }