package server import ( "encoding/json" "net/http" "path" "time" "git.espin.casa/albert/cml04-falcon-system/injector/service" "git.espin.casa/albert/cml04-falcon-system/injector/types" "github.com/zc2638/swag" "github.com/zc2638/swag/endpoint" "github.com/zc2638/swag/option" ) type Server struct { api *swag.API Url string } func PostBundleEndPoint(svc service.IService) *swag.Endpoint { return endpoint.New(http.MethodPost, "/bundle/new", endpoint.BodyR(types.PostBundleReq{}), endpoint.Response(http.StatusOK, "ok", endpoint.SchemaResponseOption(types.PostBundleRes{})), endpoint.Summary("Post bundle data to falcon system"), endpoint.Description("Post bundle data to falcon system"), endpoint.Handler(PostBundleHandler(svc)), ) } func PostBundleHandler(svc service.IService) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // request body holder req := &types.PostBundleReq{} // decode json body request if err := json.NewDecoder(r.Body).Decode(&req); err != nil { http.Error(w, "body json decoding failed", http.StatusBadRequest) return } // call bundle service res, err := svc.Bundle(r.Context(), req) if err != nil { http.Error(w, "validate user failed", http.StatusInternalServerError) return } // set content type header w.Header().Set("Content-Type", "application/json") // response w.WriteHeader(http.StatusOK) // write response if err := json.NewEncoder(w).Encode(&res); err != nil { http.Error(w, "encode response failed", http.StatusInternalServerError) return } }) } func (s *Server) Start() error { // set api handlers for p, endpoints := range s.api.Paths { http.DefaultServeMux.Handle(path.Join(s.api.BasePath, p), endpoints) } // set swagger handlers http.DefaultServeMux.Handle("/swagger/json", s.api.Handler()) patterns := swag.UIPatterns("/swagger/ui") for _, pattern := range patterns { http.DefaultServeMux.Handle(pattern, swag.UIHandler("/swagger/ui", "/swagger/json", true)) } // Crear un servidor HTTP server := http.Server{ Addr: s.Url, ReadTimeout: 5 * time.Second, // time limit for reading WriteTimeout: 5 * time.Second, // time limit for writting IdleTimeout: 5 * time.Second, } // start api go func() { if err := server.ListenAndServe(); err != nil { panic(err) } }() return nil } func NewServer(url string, svc service.IService) *Server { // create new swag api := swag.New( option.Title("CELSA 4 Falcon Bundle Injector"), option.Description("This is an implementation of a REST API server for mediciones"), option.ContactEmail("aespin@gcelsa.com"), option.Version("1.0"), option.BasePath("/api/v1"), option.License("MIT", "https://opensource.org/license/mit"), ) // add end points api.AddEndpoint( PostBundleEndPoint(svc), ) return &Server{ api: api, Url: url, } }