Skip to content

Instantly share code, notes, and snippets.

@gufranmirza
Created June 17, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gufranmirza/989b8d17e8c921c5470d100c73d2ecef to your computer and use it in GitHub Desktop.
Save gufranmirza/989b8d17e8c921c5470d100c73d2ecef to your computer and use it in GitHub Desktop.
// main.go
package main
import (
"fmt"
"encoding/json"
"log"
"net/http"
"github.com/gorilla/mux"
"io/ioutil"
)
// Article - Our struct for all articles
type Article struct {
Id string `json:"Id"`
Title string `json:"Title"`
Desc string `json:"desc"`
Content string `json:"content"`
}
var Articles []Article
// Home Page
func homePage(w http.ResponseWriter, r *http.Request){
fmt.Fprintf(w, "Welcome to the HomePage!")
fmt.Println("Endpoint Hit: homePage")
}
// Returns all articles
func returnAllArticles(w http.ResponseWriter, r *http.Request){
fmt.Println("Endpoint Hit: returnAllArticles")
json.NewEncoder(w).Encode(Articles)
}
// Return article by ID
func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
key := vars["id"]
// Loop over all of our Articles
// if the article.Id equals the key we pass in
// return the article encoded as JSON
for _, article := range Articles {
if article.Id == key {
json.NewEncoder(w).Encode(article)
}
}
}
// Create New Article
func createNewArticle(w http.ResponseWriter, r *http.Request) {
// get the body of our POST request
// unmarshal this into a new Article struct
// append this to our Articles array.
reqBody, _ := ioutil.ReadAll(r.Body)
var article Article
json.Unmarshal(reqBody, &article)
// update our global Articles array to include
// our new Article
Articles = append(Articles, article)
json.NewEncoder(w).Encode(article)
}
// Delete Article
func deleteArticle(w http.ResponseWriter, r *http.Request) {
// once again, we will need to parse the path parameters
vars := mux.Vars(r)
// we will need to extract the `id` of the article we
// wish to delete
id := vars["id"]
// we then need to loop through all our articles
for index, article := range Articles {
// if our id path parameter matches one of our
// articles
if article.Id == id {
// updates our Articles array to remove the
// article
Articles = append(Articles[:index], Articles[index+1:]...)
}
}
}
// Handle Requests
func handleRequests() {
// creates a new instance of a mux router
myRouter := mux.NewRouter().StrictSlash(true)
// replace http.HandleFunc with myRouter.HandleFunc
myRouter.HandleFunc("/", homePage)
myRouter.HandleFunc("/all", returnAllArticles)
myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("POST")
myRouter.HandleFunc("/article/{id}", returnSingleArticle)
// finally, instead of passing in nil, we want
// to pass in our newly created router as the second
// argument
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
func main() {
Articles = []Article{
Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
}
handleRequests()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment