package Controllers import ( "context" "encoding/json" "fmt" "net/http" "isl-api/sql/powerItem" "github.com/jackc/pgx/v4" ) func SetPowerItemEndpoints(mux *http.ServeMux, prefix string) { mux.HandleFunc(fmt.Sprintf("/%s", prefix), PowerItemFunc) mux.HandleFunc(fmt.Sprintf("/%s/all", prefix), PowerItemAll) } func PowerItemFunc(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: fmt.Fprintf(w, "Hello") // handle a GET case http.MethodPost: var newItem powerItem.AddNewItemWithIDParams err := json.NewDecoder(r.Body).Decode(&newItem) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } fmt.Fprintf(w, "%+v", newItem) // handle a POST case http.MethodOptions: w.Header().Set("Allow", "GET, POST, OPTIONS") w.WriteHeader(http.StatusNoContent) default: w.Header().Set("Allow", "GET, POST, OPTIONS") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: ctx := context.TODO() conn, err := pgx.Connect(ctx, "postgres://isl:development@localhost:5432") if err != nil { panic(err) } q := powerItem.NewQuerier(conn) rows, err := q.GetAllItems(ctx) if err != nil { panic(err) } data, err := json.Marshal(rows) if err != nil { panic(err) } w.Header().Add("Content-Type", "application/json") fmt.Fprintf(w, string(data)) case http.MethodOptions: w.Header().Set("Allow", "GET, OPTIONS") w.WriteHeader(http.StatusNoContent) default: w.Header().Set("Allow", "GET, OPTIONS") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } }