Skip to content

Instantly share code, notes, and snippets.

@elliotforbes
Created February 8, 2018 16:04
Show Gist options
  • Save elliotforbes/e241eaa8cc9d7bf3ec75b333e891d422 to your computer and use it in GitHub Desktop.
Save elliotforbes/e241eaa8cc9d7bf3ec75b333e891d422 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type User struct {
gorm.Model
Name string
Email string
}
func allUsers(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
var users []User
db.Find(&users)
fmt.Println("{}", users)
json.NewEncoder(w).Encode(users)
}
func newUser(w http.ResponseWriter, r *http.Request) {
fmt.Println("New User Endpoint Hit")
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
vars := mux.Vars(r)
name := vars["name"]
email := vars["email"]
fmt.Println(name)
fmt.Println(email)
db.Create(&User{Name: name, Email: email})
fmt.Fprintf(w, "New User Successfully Created")
}
func deleteUser(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
vars := mux.Vars(r)
name := vars["name"]
var user User
db.Where("name = ?", name).Find(&user)
db.Delete(&user)
fmt.Fprintf(w, "Successfully Deleted User")
}
func updateUser(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
vars := mux.Vars(r)
name := vars["name"]
email := vars["email"]
var user User
db.Where("name = ?", name).Find(&user)
user.Email = email
db.Save(&user)
fmt.Fprintf(w, "Successfully Updated User")
}
func handleRequests() {
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/users", allUsers).Methods("GET")
myRouter.HandleFunc("/user/{name}", deleteUser).Methods("DELETE")
myRouter.HandleFunc("/user/{name}/{email}", updateUser).Methods("PUT")
myRouter.HandleFunc("/user/{name}/{email}", newUser).Methods("POST")
log.Fatal(http.ListenAndServe(":8081", myRouter))
}
func initialMigration() {
db, err := gorm.Open("sqlite3", "test.db")
if err != nil {
fmt.Println(err.Error())
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&User{})
}
func main() {
fmt.Println("Go ORM Tutorial")
initialMigration()
// Handle Subsequent requests
handleRequests()
}
@sparkidea25
Copy link

syntax error: unexpected EOF, expecting }This is throwing an error

@TopSwagCode
Copy link

Post and Put should use request body and not url / querystring parameters

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment