Skip to content

Instantly share code, notes, and snippets.

@Duncanian
Last active June 6, 2023 20:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Duncanian/0f71727b7aae48aa270178400ca4b94a to your computer and use it in GitHub Desktop.
Save Duncanian/0f71727b7aae48aa270178400ca4b94a to your computer and use it in GitHub Desktop.
The full main.go file for go-rest-api
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
)
type event struct {
ID string `json:"ID"`
Title string `json:"Title"`
Description string `json:"Description"`
}
type allEvents []event
var events = allEvents{
{
ID: "1",
Title: "Introduction to Golang",
Description: "Come join us for a chance to learn how golang works and get to eventually try it out",
},
}
func homeLink(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome home!")
}
func createEvent(w http.ResponseWriter, r *http.Request) {
var newEvent event
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Kindly enter data with the event title and description only in order to update")
}
json.Unmarshal(reqBody, &newEvent)
events = append(events, newEvent)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newEvent)
}
func getOneEvent(w http.ResponseWriter, r *http.Request) {
eventID := mux.Vars(r)["id"]
for _, singleEvent := range events {
if singleEvent.ID == eventID {
json.NewEncoder(w).Encode(singleEvent)
}
}
}
func getAllEvents(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(events)
}
func updateEvent(w http.ResponseWriter, r *http.Request) {
eventID := mux.Vars(r)["id"]
var updatedEvent event
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Kindly enter data with the event title and description only in order to update")
}
json.Unmarshal(reqBody, &updatedEvent)
for i, singleEvent := range events {
if singleEvent.ID == eventID {
singleEvent.Title = updatedEvent.Title
singleEvent.Description = updatedEvent.Description
events = append(events[:i], singleEvent)
json.NewEncoder(w).Encode(singleEvent)
}
}
}
func deleteEvent(w http.ResponseWriter, r *http.Request) {
eventID := mux.Vars(r)["id"]
for i, singleEvent := range events {
if singleEvent.ID == eventID {
events = append(events[:i], events[i+1:]...)
fmt.Fprintf(w, "The event with ID %v has been deleted successfully", eventID)
}
}
}
func main() {
initEvents()
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/event", createEvent).Methods("POST")
router.HandleFunc("/events", getAllEvents).Methods("GET")
router.HandleFunc("/events/{id}", getOneEvent).Methods("GET")
router.HandleFunc("/events/{id}", updateEvent).Methods("PATCH")
router.HandleFunc("/events/{id}", deleteEvent).Methods("DELETE")
log.Fatal(http.ListenAndServe(":8080", router))
}
@thomas-hoer
Copy link

Nice introduction, but you have to remove initEvents() in line 93 for a working example

@gilly7
Copy link

gilly7 commented Dec 22, 2021

helpful article

@docentedev
Copy link

docentedev commented Apr 30, 2022

@thomas-hoer or add a new func and change

var events = allEvents{
	{
		ID:          "1",
		Title:       "Introduction to Golang",
		Description: "Come join us for a chance to learn how golang works and get to eventually try it out",
	},
}

to

var events = allEvents{}
func initEvents() {
	newEvent := event{
		ID:          "1",
		Title:       "Introduction to Golang",
		Description: "Come join us for a chance to learn how golang works and get to eventually try it out",
	}
	events = append(events, newEvent)
}

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