70
app.go
70
app.go
@@ -1,70 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/postgres"
|
||||
)
|
||||
|
||||
type Besucher struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Message string `json:"message"`
|
||||
Come bool `json:"come"`
|
||||
}
|
||||
|
||||
type App struct {
|
||||
db *gorm.DB
|
||||
r *mux.Router
|
||||
}
|
||||
|
||||
func (a *App) start() {
|
||||
a.db.AutoMigrate()
|
||||
|
||||
a.r.HandleFunc("/besucher", a.getAllBesucher).Methods("GET")
|
||||
a.r.HandleFunc("/besucher", a.addBesucher).Methods("POST")
|
||||
log.Fatal(http.ListenAndServe(":3001", a.r))
|
||||
}
|
||||
|
||||
func (a *App) getAllBesucher(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
var all []Besucher
|
||||
err := a.db.Find(&all).Error
|
||||
if err != nil {
|
||||
sendErr(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
err = json.NewEncoder(w).Encode(all)
|
||||
if err != nil {
|
||||
sendErr(w, http.StatusInternalServerError, err.Error())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (a *App) addBesucher(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
var s Besucher
|
||||
err := json.NewDecoder(r.Body).Decode(&s)
|
||||
if err != nil {
|
||||
sendErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
s.ID = uuid.New().String()
|
||||
err = a.db.Save(&s).Error
|
||||
if err != nil {
|
||||
sendErr(w, http.StatusInternalServerError, err.Error())
|
||||
|
||||
} else {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
}
|
||||
|
||||
func sendErr(w http.ResponseWriter, code int, message string) {
|
||||
resp, _ := json.Marshal(map[string]string{"error": message})
|
||||
http.Error(w, string(resp), code)
|
||||
}
|
||||
Reference in New Issue
Block a user