-
-
Save rnubel/4d0e19389186973dcab761d9fac2bed8 to your computer and use it in GitHub Desktop.
Refactored Blog API
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" | |
"log" | |
"net/http" | |
"github.com/gorilla/mux" | |
"gorm.io/driver/postgres" | |
"gorm.io/gorm" | |
) | |
// Post is a GORM model representing a blog post. | |
type Post struct { | |
gorm.Model | |
Title string `json:"title"` | |
Body string `json:"body"` | |
} | |
func main() { | |
var err error | |
db, err := gorm.Open(postgres.Open("host=localhost user=postgres password=postgres dbname=myblog port=5432 sslmode=disable"), &gorm.Config{}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
router := mux.NewRouter() | |
router.HandleFunc("/posts", listPostsHandler(db)).Methods("GET") | |
router.HandleFunc("/posts", createPostHandler(db)).Methods("POST") | |
router.HandleFunc("/posts/{id}", getPostHandler(db)).Methods("GET") | |
log.Println("Listening on port 3000") | |
log.Fatal(http.ListenAndServe(":3000", router)) | |
} | |
// handleApiError renders a JSON error and sets the HTTP status code. | |
func handleApiError(w http.ResponseWriter, err error, code int) { | |
w.Header().Set("Content-Type", "application/json") | |
w.WriteHeader(code) | |
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()}) | |
} | |
func listPostsHandler(db *gorm.DB) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
var posts []Post | |
db.Find(&posts) | |
// convert the posts to JSON | |
postsJSON, err := json.Marshal(posts) | |
if err != nil { | |
handleApiError(w, err, 500) | |
} | |
w.Write(postsJSON) | |
} | |
} | |
func createPostHandler(db *gorm.DB) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
var post Post | |
json.NewDecoder(r.Body).Decode(&post) | |
db.Create(&post) | |
// convert the post to JSON | |
postJSON, err := json.Marshal(post) | |
if err != nil { | |
handleApiError(w, err, 500) | |
} | |
w.WriteHeader(201) | |
w.Write(postJSON) | |
} | |
} | |
func getPostHandler(db *gorm.DB) http.HandlerFunc { | |
return func(w http.ResponseWriter, r *http.Request) { | |
vars := mux.Vars(r) | |
var post Post | |
db.First(&post, vars["id"]) | |
// convert the post to JSON | |
postJSON, err := json.Marshal(post) | |
if err != nil { | |
handleApiError(w, err, 500) | |
} | |
w.Write(postJSON) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment