github.com/christoph-karpowicz/db_mediator@v0.0.0-20210207102849-61a28a1071d8/internal/server/application/run_synch_handler.go (about)

     1  package application
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"log"
     7  	"net/http"
     8  	"strconv"
     9  )
    10  
    11  type runSynchHandler struct {
    12  	app *Application
    13  }
    14  
    15  func (h *runSynchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    16  	synchType, ok := r.URL.Query()["type"]
    17  	if !ok || len(synchType[0]) < 1 {
    18  		log.Fatalln("[http request] ERROR: URL param 'type' is missing.")
    19  	}
    20  
    21  	run, ok := r.URL.Query()["run"]
    22  	if !ok || len(run[0]) < 1 {
    23  		log.Fatalln("[http request] ERROR: URL param 'run' is missing.")
    24  	}
    25  
    26  	simulationStr, ok := r.URL.Query()["simulation"]
    27  	if !ok {
    28  		simulationStr = []string{"false"}
    29  	}
    30  	simulation, err := strconv.ParseBool(simulationStr[0])
    31  	if err != nil {
    32  		log.Fatalln("[http request] ERROR: Wrong 'simulation' URL param value.")
    33  	}
    34  
    35  	if simulation && synchType[0] == "ongoing" {
    36  		log.Fatalln("[http request] ERROR: Cannot start an ongoing synchronization simulation.")
    37  	}
    38  
    39  	resChan := createResponseChannel()
    40  	go h.app.runSynch(resChan, synchType[0], run[0], simulation)
    41  
    42  	response := <-resChan
    43  	responseJSON, err := json.Marshal(response)
    44  	if err != nil {
    45  		panic("Error while marshalling response.")
    46  	}
    47  
    48  	fmt.Fprintf(w, "%s", responseJSON)
    49  }