Browse Source

Global randomdata POST and GET

main
Unbewohnte 3 years ago
parent
commit
bae89bce96
  1. 18
      dbHandle/handle.go
  2. 14
      randomData/randomData.go

18
dbHandle/handle.go

@ -22,6 +22,7 @@ func (db *DB) GetEverything() ([]*randomdata.RandomData, error) {
var id uint
var title string
var text string
rows.Scan(&id, &title, &text)
var randomData = randomdata.RandomData{
@ -30,8 +31,6 @@ func (db *DB) GetEverything() ([]*randomdata.RandomData, error) {
Text: text,
}
fmt.Println(id, title, text)
contents = append(contents, &randomData)
}
@ -88,17 +87,28 @@ func (db *DB) HandleGlobalWeb(w http.ResponseWriter, r *http.Request) {
log.Printf("Could not create a row: %s", err)
}
w.WriteHeader(http.StatusAccepted)
return
case http.MethodGet:
data, err := db.GetEverything()
randomDatas, err := db.GetEverything()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not retrieve db contents: %s\n", err)
return
}
w.Write()
randomDatasJsonBytes, err := randomdata.ToJsonAll(randomDatas)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("Could not convert to json: %s\n", err)
return
}
w.Write(randomDatasJsonBytes)
return
default:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
}

14
randomData/randomData.go

@ -33,3 +33,17 @@ func (rd *RandomData) ToJson() ([]byte, error) {
return bytes, nil
}
// Convert all rdatas to []byte
func ToJsonAll(rdatas []*RandomData) ([]byte, error) {
var rdatasBytes []byte
for _, rdata := range rdatas {
jsonBytes, err := rdata.ToJson()
if err != nil {
return nil, err
}
rdatasBytes = append(rdatasBytes, jsonBytes...)
}
return rdatasBytes, nil
}

Loading…
Cancel
Save