// package serv_http -- веб-сервер сервиса (графика и АПИ) package serv_http import ( "fmt" "io" "log" "net/http" "adt/pkg/entities/order" "adt/pkg/types" ) // ServHttp -- веб-сервер сервиса (графика и АПИ) type ServHttp struct { mux *http.ServeMux proc types.IServProcess } // NewServHttp -- возвращает новый объект веб-сервера func NewServHttp(servProcess types.IServProcess) (*ServHttp, error) { log.Println("NewServHttp()") if servProcess == nil { return nil, fmt.Errorf("NewServHttp(): IServProcess==nil") } sf := &ServHttp{ mux: http.NewServeMux(), proc: servProcess, } sf.mux.HandleFunc("/orders", sf.createOrder) return sf, nil } // Run -- запускает веб-сервер в работу func (sf *ServHttp) Run() error { log.Println("ServHttp.Run(): on http://localhost:8090/") err := http.ListenAndServe(":8090", sf.mux) if err != nil { return fmt.Errorf("ServHttp.Run(): in ListenAndServe, err=\n\t%w", err) } return nil } // Создаёт новый заказ func (sf *ServHttp) createOrder(w http.ResponseWriter, r *http.Request) { binData, err := io.ReadAll(r.Body) if err != nil { msg := fmt.Sprintf("ERROR ServHttp.createOrder(): in ioutil.ReadAll, err=\n\t%v\n", err) http.Error(w, msg, http.StatusBadRequest) log.Println(msg) return } var newOrder types.IHotelRoomOrder newOrder, err = order.Unmarshall(binData) if err != nil { msg := fmt.Sprintf("ERROR ServHttp.createOrder(): in order.Unmarshal, err=\n\t%v\n", err) http.Error(w, msg, http.StatusBadRequest) log.Println(msg) return } err = sf.proc.MakeHotelRoomOrder(newOrder) if err != nil { msg := fmt.Sprintf("ERROR ServHttp.createOrder(): in proc.MakeHotelRoomOrder, err=\n\t%v\n", err) http.Error(w, msg, http.StatusBadRequest) log.Println(msg) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) _, err = w.Write(newOrder.Marshall()) if err != nil { msg := fmt.Sprintf("ERROR ServHttp.createOrder(): in w.Write response, err=\n\t%v\n", err) http.Error(w, msg, http.StatusBadRequest) log.Println(msg) return } log.Printf("ServHttp.createOrder(): order=%q, created ok\n", newOrder.Id()) }