Tuesday, November 24, 2020

Belajar Golang #04 - Membuat Restapi CRUD Golang + Mysql

https://play-lh.googleusercontent.com/edQ8_8or0qX3JymcLz5jrHskKXLGjj7b7lGYuBW-oUMmK75vspumKniy6gukdOuzbcNl=s180

Install library :

go get github.com/go-sql-driver/mysql
go get github.com/gorilla/mux

 

Main.go

package main

import (
    "fmt"
    "log"
    "net/http"
        "encoding/json"

    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
)

func main() {

    router := mux.NewRouter()
    router.HandleFunc("/getusers", returnAllUsers).Methods("GET")
        router.HandleFunc("/get1user/{id}", return1User).Methods("GET")
        router.HandleFunc("/get1user2/{id2}", return1User2).Methods("POST")
        router.HandleFunc("/users", insertUsersMultipart).Methods("POST")
        router.HandleFunc("/users",updateUsersMultipart).Methods("PUT")
        router.HandleFunc("/users",deleteUsersMultipart).Methods("DELETE")
    http.Handle("/", router)
    fmt.Println("Connected to port 8080")
    log.Fatal(http.ListenAndServe(":8080", router))

}


func returnAllUsers(w http.ResponseWriter, r *http.Request) {
    var users Users
    var arr_user []Users
    var response Response

    db := connect()
    defer db.Close()

    rows, err := db.Query("Select id,first_name,last_name from person")
    if err != nil {
        log.Print(err)
    }

    for rows.Next() {
        if err := rows.Scan(&users.Id, &users.FirstName, &users.LastName); err != nil {
            log.Fatal(err.Error())

        } else {
            arr_user = append(arr_user, users)
        }
    }

    response.Status = 1
    response.Message = "Success"
    response.Data = arr_user

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)
}

func return1User(w http.ResponseWriter, r *http.Request) {
    var users Users
    var arr_user []Users
    var response Response

    db := connect()
    defer db.Close()

        vars := mux.Vars(r)
    id := vars["id"]

    rows, err := db.Query("Select id,first_name,last_name from person where id="+id)
    if err != nil {
        log.Print(err)
    }
        var status=0
        var hasil="gagal"
    for rows.Next() {
        if err := rows.Scan(&users.Id, &users.FirstName, &users.LastName); err != nil {
            log.Fatal(err.Error())
        } else {
            arr_user = append(arr_user, users)
                        status=1
                        hasil="sukses"
        }
    }

    response.Status = status
    response.Message = hasil
    response.Data = arr_user

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)

}


func return1User2(w http.ResponseWriter, r *http.Request) {
        var users Users
        var arr_user []Users
        var response Response

        db := connect()
        defer db.Close()

        vars := mux.Vars(r)
        id := vars["id2"]

        rows, err := db.Query("Select id,first_name,last_name from person where id="+id)
        if err != nil {
                log.Print(err)
        }
        var status=0
        var hasil="gagal"
        for rows.Next() {
                if err := rows.Scan(&users.Id, &users.FirstName, &users.LastName); err != nil {
                        log.Fatal(err.Error())
                } else {
                        arr_user = append(arr_user, users)
                        status=1
                        hasil="sukses"
                }
        }

        response.Status = status
        response.Message = hasil
        response.Data = arr_user

        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(response)

}


 

Mysql.go


package main

import (
    "database/sql"
    "log"
        "fmt"
)

func connect() *sql.DB {
    db, err := sql.Open("mysql", "root:password@tcp(host:3306)/namadb")

    if err != nil {
        log.Fatal(err)
    }
        fmt.Println("connect db ok !")
    return db
}
 

 

 

 

data.go

package main

import (
    "encoding/json"
    "log"
        "fmt"
    "net/http"
)


func insertUsersMultipart(w http.ResponseWriter, r *http.Request) {
  var response Response
        fmt.Println("insert processing");
       
    db := connect()
    defer db.Close()

         err := r.ParseForm()
    if err != nil {
        panic(err)
    }
        first_name := r.Form.Get("first_name")
        last_name := r.Form.Get("last_name")

    _, err = db.Exec("INSERT INTO person (first_name, last_name) values (?,?)",
        first_name,
        last_name,
    )

    if err != nil {
        log.Print(err)
    }

    response.Status = 1
    response.Message = "Success Add"
    log.Print("Insert data to database")

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)

}

func updateUsersMultipart(w http.ResponseWriter, r *http.Request) {
    var response Response

    db := connect()
    defer db.Close()

        err := r.ParseForm()
        if err != nil {
                panic(err)
        }
        id := r.Form.Get("user_id")
        first_name := r.Form.Get("first_name")
        last_name := r.Form.Get("last_name")


    _, err = db.Exec("UPDATE person set first_name = ?, last_name = ? where id = ?",
        first_name,
        last_name,
        id,
    )

    if err != nil {
        log.Print(err)
    }

    response.Status = 1
    response.Message = "Success Update Data"
    log.Print("Update data to database")

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)

}

func deleteUsersMultipart(w http.ResponseWriter, r *http.Request) {
    var response Response

    db := connect()
    defer db.Close()

        err := r.ParseForm()
        if err != nil {
                panic(err)
        }
        id := r.Form.Get("user_id")

    _, err = db.Exec("DELETE from person where id = ?",
        id,
    )

    if err != nil {
        log.Print(err)
    }

    response.Status = 1
    response.Message = "Success Delete Data"
    log.Print("Delete data to database")

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(response)

}


 

Cek dengan menggunakan postman

 Update Data

 

 

 

Add Data

 

 

 Delete Data

 

 

Get all User


 

 Testing insert dengan menggunakan curl:

curl --data "first_name=keke3&last_name=keke3" -X POST http://localhost:8080/users


Sumber : https://kiddyxyz.medium.com

No comments:

Post a Comment

Membuat Counter mundur menuju Azan dengan Arduino Wemos

Membuat Counter Mundur Menuju Azan dengan Arduino Wemos  #include <Wire.h> #include "RTClib.h" #include "SPI.h" #i...