Hello, I have been looking for tutorials on Golang TDD Rest API but I have
not been finding any.
Am not interested in using a framework.
Am interested in a TDD CRUD REST API.
The test I have written returns
controllers/admin.go:18: undefined: a in a.DB
This is what I have so far.
controller/admin.go
func CreateAdmin(w http.ResponseWriter, r *http.Request) {
var admin models.Admin
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&admin); err != nil {
helpers.RespondWithError(w, http.StatusBadRequest, "Invalid request
payload")
return
}
defer r.Body.Close()
if err := admin.CreateAdmin(a.DB); err != nil {
helpers.RespondWithError(w, http.StatusInternalServerError, err.Error())
return
}
helpers.RespondWithJSON(w, http.StatusCreated, admin)
}
model/admin.go
type Admin struct {
ID int `json:"id"`
Name string `json:"name"`
Company string `json:"company"`
Username string `json:"username"`
Password string `json:"password"`
}
func (p *Admin) CreateAdmin(db *sql.DB) error {
err := db.QueryRow("INSERT INTO admins(name, company, username, password)
VALUES($1, $2, $3, $4) RETURNING id", p.Name, p.Company, p.Username,
p.Password).Scan(&p.ID)
if err != nil {
return err
}
return nil
}
main.go
func main() {
router := mux.NewRouter()
// admin routes
router.HandleFunc("/admin", controllers.CreateAdmin).Methods("GET")
log.Fatal(http.ListenAndServe(":9000", router))
}
tests/admin_test.go
func TestCreateAdmin(t *testing.T) {
payload := []byte(`{"name":"new admin", "company":"localhost",
"username":"[email protected]", "password":"admin"}`)
request, err := http.NewRequest("POST", "/admin", bytes.NewBuffer(payload))
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
handler := http.HandlerFunc(controllers.CreateAdmin)
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Errorf("bad response code, wanted %v got %v", recorder.Code,
http.StatusOK)
}
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.