Create a CRUD app using Golang

Photo by Jakob Owens on Unsplash

Create a CRUD app using Golang

Today we will be making a CRUD app using GO-lang, CRUD stands for Create Read Update Delete.

In this app using GO, we will be making a movie directory here you can fetch any movie or all movies and then read/update/delete them depending on the use you have.

Technologies we will be working on:

  • GO

  • Postman

  • Windows Powershell

Going through the process step by step, start by making a new folder in the source root directory of GO, Open Windows Powershell>>cd go>>cd src>>mkdir go-crud Once we are done creating the go-crud folder, we will start coding, to open your ide directly using PowerShell, simply write code . , this will open your default code editor.

PS C:\Users\Ayush> cd go
PS C:\Users\Ayush\go> cd src
PS C:\Users\Ayush\go\src> cd go-crud
PS C:\Users\Ayush\go\src> code .

After that, start by creating the main go file where all the code will be there, Start by importing all the packages,

package main


import(
    "fmt"
    "log"
    "encoding/json"
    "math/rand"
    "net/http"
    "strconv"
    "github.com/gorilla/mux"
)

Declare all the variables in the movie and director functions respectively and don't forget to use struct. When we assign a struct variable to another struct variable, a new copy of the struct is created. Likewise, when we pass a struct to another function, the function receives a new copy of the struct.

type Movie struct{
    ID string `json: "id`
    Isbn string `json: "isbn"`
    Title string `json: "title"`
    Director *Director `json "director"`
}

type Director struct {
    Firstname string `json:"firstname"`
    Lastname string `json:"lastname"`

}

Then, declare the variable movies in the form array, since we want to edit or use them one by one, therefore we will be referring to them as indexes using []

var movies []Movie

Let's set the route for all the keywords we will be using like CREATE, UPDATE, DELETE, etc : followed by setting the port route, this will be where we will be able to view all the results,

func main(){

    r := mux.NewRouter()

    r.HandleFunc("/movies", getMovies).Methods("GET")
    r.HandleFunc("/movie(id)", getMovie).Methods("GET")
    r.HandleFunc("/movies", createMovie).Methods("POST")
    r.HandleFunc("/movies(id)", updateMovie).Methods("PUT")
    r.HandleFunc("/movies(id)", deleteMovie).Methods("DELETE")



    fmt.Println("Starting server at port 8000")
    log.Fatal(http.ListenAndServe(":8000", r))
}

Now we will give functionality to all the keywords declared before and set them to what will give what result: Staring with getMovies func:

func getMovies(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(movies)
}

deleteMovies:

func deleteMovie (w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, item := range movies {
        if item.ID == params["id"]{
            movies = append(movies[:index], movies[index+1:]...)
            break
        }
    }
    json.NewEncoder(w).Encode(movies)

}

getMovie func:

func getMovie(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for _, item := range movies {
        if item.ID == params["id"]{
            json.NewEncoder(w).Encode(item)
            return
        }
    }
}

createMovie func:

func createMovie ( w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    var movie Movie
    _ = json.NewDecoder(r.Body).Decode(&movie)
    movie.ID = strconv.Itoa(rand.Intn(100000000))
    movies = append(movies, movie)
    json.NewEncoder(w).Encode(movie)

}

updateMovie:

func updateMovie( w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    for index, item := range movies{
        if item.ID == params["ID"]{
            movies = append(movies[:index], movies[index+1:]...)
            var movie Movie
            _ = json.NewDecoder(r.Body).Decode(&movie)
            movie.ID = params["id"]
            movies = append(movies, movie)
            json.NewEncoder(w).Encode(movie)
            return

        }
    }
}

At last, we will give dummy data to test our application, you can give any data you want, here's my dummy data:

movies = append(movies, Movie{ID: "1", Isbn: "438227", Title:"Movie One", Director: &Director{Firstname:"John", Lastname: "Doe"}})
    movies = append(movies, Movie{ID: "2", Isbn: "845545", Title:"Movie 2", Director: &Director{Firstname:"Alec", Lastname: "Benjamin"}})

Our code is completed, and now we want to test it, Let's use POSTMAN, you can install postman from the link given below, Before testing, we will be needing to run our code, for that open Powershell, run go build>>go run $file name

image.png You can ignore the error, I just made a small mistake, but as you can see at the end, the code is working perfectly without any error at port 8000.

Make a workspace and then create folders with Add requests with all the values which we gave in the code above, it will look something like this:

image.png

Select a value and then in the GET request option paste your port followed by the value like:

http://localhost:8000/movies

Click SEND and let the magic happen!

image.png You will get the desired data.