mirror of
https://forgejo.merr.is/annika/isl-api.git
synced 2025-12-11 15:03:16 -05:00
Mostly Initial Setup And Testing Stuff
This commit is contained in:
parent
8c147b23d8
commit
d52d9968ba
12 changed files with 502 additions and 0 deletions
73
Controllers/PowerItemController.go
Normal file
73
Controllers/PowerItemController.go
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue