99 lines
2.6 KiB
Go
99 lines
2.6 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/exec"
|
|
"recipe-manager/data"
|
|
"recipe-manager/routers"
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/cors"
|
|
)
|
|
|
|
type Server struct {
|
|
server *http.Server
|
|
data *data.Data
|
|
}
|
|
|
|
func NewServer(port uint) *Server {
|
|
return &Server{
|
|
server: &http.Server{Addr: fmt.Sprintf(":%d", port)},
|
|
data: data.NewData(),
|
|
}
|
|
}
|
|
|
|
func (s *Server) Run() error {
|
|
|
|
s.server.Handler = createHandler()
|
|
log.Printf("Server running on %s", s.server.Addr)
|
|
return s.server.ListenAndServe()
|
|
}
|
|
|
|
func createHandler() http.Handler {
|
|
r := chi.NewRouter()
|
|
r.Use(cors.Handler(cors.Options{
|
|
AllowedOrigins: []string{"https://*", "http://*"},
|
|
AllowCredentials: true,
|
|
ExposedHeaders: []string{"Content-Type"},
|
|
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
|
|
}))
|
|
r.Post("/merge", func(w http.ResponseWriter, r *http.Request) {
|
|
var targetMap map[string]interface{}
|
|
err := json.NewDecoder(r.Body).Decode(&targetMap)
|
|
if err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
log.Fatalln("Merge request failed: ", err)
|
|
return
|
|
}
|
|
log.Println(targetMap)
|
|
master_version := targetMap["master"].(string)
|
|
dev_version := targetMap["dev"].(string)
|
|
|
|
// find target file in the cofffeemachineConfig
|
|
if _, err := os.Stat("coffeemachineConfig/coffeethai02_" + master_version + ".json"); err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
log.Fatalln("Merge request failed. Master file not found: ", err)
|
|
return
|
|
}
|
|
if _, err := os.Stat("coffeemachineConfig/coffeethai02_" + dev_version + ".json"); err != nil {
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
log.Fatalln("Merge request failed. Dev file not found: ", err)
|
|
return
|
|
}
|
|
|
|
repo_path := "coffeemachineConfig/coffeethai02_"
|
|
master_path := repo_path + master_version + ".json"
|
|
dev_path := repo_path + dev_version + ".json"
|
|
|
|
// output path
|
|
output_path := ""
|
|
|
|
// changelog path
|
|
changelog_path := ""
|
|
|
|
// TODO: Call merge api if found
|
|
err = exec.Command("python", "merge", master_path, dev_path, output_path, changelog_path).Run()
|
|
if err != nil {
|
|
log.Fatalln("Merge request failed. Python merge failed: ", err)
|
|
}
|
|
})
|
|
rr := routers.NewRecipeRouter(data.NewData())
|
|
rr.Route(r)
|
|
|
|
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Add("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusNotFound)
|
|
json.NewEncoder(w).Encode(map[string]string{"message": fmt.Sprintf("path %s are not exits", r.RequestURI)})
|
|
})
|
|
|
|
return r
|
|
}
|
|
|
|
func (s *Server) Shutdown(ctx context.Context) error {
|
|
return s.server.Shutdown(ctx)
|
|
}
|