Created
February 16, 2023 05:53
-
-
Save goodylili/63a34fb9b8d449e3f4ce96dc5d8825d0 to your computer and use it in GitHub Desktop.
CRUD RESTful API in Go with the Gorilla Mux Package - Article for RedGate's Simple Talk Blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
"gorm.io/driver/sqlite" | |
"gorm.io/gorm" | |
) | |
type Human struct { | |
ID uint `gorm:"primaryKey"` | |
Age int `json:"age"` | |
Name string `json:"name"` | |
} | |
var ( | |
db *gorm.DB | |
err error | |
) | |
func DBConnection() error { | |
db, err = gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) | |
if err != nil { | |
return err | |
} | |
err = db.AutoMigrate(&Human{}) | |
if err != nil { | |
return err | |
} | |
return nil | |
} | |
func getHuman(writer http.ResponseWriter, request *http.Request) { | |
vars := mux.Vars(request) | |
id := vars["id"] | |
var human Human | |
db.First(&human, id) | |
err := json.NewEncoder(writer).Encode(human) | |
if err != nil { | |
log.Println(err) | |
} | |
} | |
func createHuman(writer http.ResponseWriter, request *http.Request) { | |
var human Human | |
err = json.NewDecoder(request.Body).Decode(&human) | |
if err != nil { | |
log.Println(err) | |
} | |
db.Create(&human) | |
err := json.NewEncoder(writer).Encode(human) | |
if err != nil { | |
log.Println(err) | |
} | |
} | |
func updateHuman(writer http.ResponseWriter, request *http.Request) { | |
vars := mux.Vars(request) | |
id := vars["id"] | |
var human Human | |
db.First(&human, id) | |
err := json.NewDecoder(request.Body).Decode(&human) | |
if err != nil { | |
log.Println(err) | |
} | |
db.Save(&human) | |
err = json.NewEncoder(writer).Encode(human) | |
if err != nil { | |
log.Println(err) | |
} | |
} | |
func deleteHuman(writer http.ResponseWriter, request *http.Request) { | |
vars := mux.Vars(request) | |
id := vars["id"] | |
db.Delete(&Human{}, id) | |
_, err := fmt.Fprintf(writer, "Human with ID = %s has been deleted", id) | |
if err != nil { | |
log.Println(err) | |
} | |
} | |
func main() { | |
err := DBConnection() | |
if err != nil { | |
log.Fatal("Database connection error", err) | |
} | |
router := mux.NewRouter() | |
router.HandleFunc("/humans/{id}", getHuman).Methods("GET") | |
router.HandleFunc("/humans", createHuman).Methods("POST") | |
router.HandleFunc("/humans/{id}", updateHuman).Methods("PUT") | |
router.HandleFunc("/humans/{id}", deleteHuman).Methods("DELETE") | |
log.Fatal(http.ListenAndServe(":8080", router)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment