Advertisement
Uhuuuyy

main.go

Jul 4th, 2023
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 7.03 KB | Source Code | 0 0
  1. package main
  2.  
  3. import (
  4.     "database/sql"
  5.     "encoding/json"
  6.     "fmt"
  7.     "log"
  8.     "mime"
  9.     "net/http"
  10.     "os"
  11.     "path/filepath"
  12.     "time"
  13.  
  14.     _ "github.com/go-sql-driver/mysql"
  15.     "github.com/gorilla/mux"
  16. )
  17.  
  18. type spaHandler struct {
  19.     staticPath string
  20.     indexPath  string
  21. }
  22. type Mahasiswa struct {
  23.     Id      int    `json:"id"`
  24.     Npm     string `json:"npm"`
  25.     Nama    string `json:"nama"`
  26.     Kelas   string `json:"kelas"`
  27.     Profile string `json:"profile"`
  28. }
  29. type ResponseAllData struct {
  30.     Status bool        `json:"status"`
  31.     Data   []Mahasiswa `json:"data"`
  32. }
  33. type ResponseData struct {
  34.     Status bool      `json:"status"`
  35.     Data   Mahasiswa `json:"data"`
  36. }
  37. type ResponseMessage struct {
  38.     Status  bool   `json:"status"`
  39.     Message string `json:"message"`
  40. }
  41. type ResponseError struct {
  42.     Status bool   `json:"status"`
  43.     Error  string `json:"error"`
  44. }
  45.  
  46. func dbConn() (db *sql.DB) {
  47.     dbDriver := "mysql"
  48.     dbName := "db_dimasraihan"
  49.     dbUser := "root"
  50.     dbPass := ""
  51.     db, err := sql.Open(dbDriver, dbUser+":"+dbPass+"@tcp(localhost)/"+dbName)
  52.     if err != nil {
  53.         panic(err.Error())
  54.     }
  55.     return db
  56. }
  57. func getAllMahasiswa(w http.ResponseWriter, r *http.Request) {
  58.     w.Header().Set("Content-type", "application/json")
  59.     var response ResponseAllData
  60.     var mahasiswa Mahasiswa
  61.     var mhs []Mahasiswa
  62.     db := dbConn()
  63.     rows, err := db.Query("SELECT * FROM mahasiswa")
  64.     defer db.Close()
  65.     if err != nil {
  66.         log.Print(err.Error())
  67.     }
  68.     for rows.Next() {
  69.         err := rows.Scan(&mahasiswa.Id, &mahasiswa.Npm, &mahasiswa.Nama, &mahasiswa.Kelas, &mahasiswa.Profile)
  70.         if err != nil {
  71.             log.Print(err.Error())
  72.         } else {
  73.             mhs = append(mhs, mahasiswa)
  74.         }
  75.     }
  76.     response.Status = true
  77.     response.Data = mhs
  78.     json.NewEncoder(w).Encode(response)
  79.     return
  80. }
  81. func getMahasiswa(w http.ResponseWriter, r *http.Request) {
  82.     w.Header().Set("Content-type", "application/json")
  83.     var response ResponseData
  84.     var responseErr ResponseError
  85.     var mahasiswa Mahasiswa
  86.     db := dbConn()
  87.     defer db.Close()
  88.     params := mux.Vars(r)
  89.     rows := db.QueryRow("SELECT * FROM mahasiswa WHERE id=?", params["id"])
  90.     err := rows.Scan(&mahasiswa.Id, &mahasiswa.Npm, &mahasiswa.Nama, &mahasiswa.Kelas, &mahasiswa.Profile)
  91.     if err != nil && err == sql.ErrNoRows {
  92.         responseErr.Status = false
  93.         responseErr.Error = "Mahasiswa tidak ditemukan"
  94.         w.WriteHeader(http.StatusNotFound)
  95.         json.NewEncoder(w).Encode(responseErr)
  96.         return
  97.     }
  98.     response.Status = true
  99.     response.Data = mahasiswa
  100.     json.NewEncoder(w).Encode(response)
  101.     return
  102. }
  103. func getMahasiswaByName(w http.ResponseWriter, r *http.Request) {
  104.     w.Header().Set("Content-type", "application/json")
  105.     var mahasiswa Mahasiswa
  106.     var mhs []Mahasiswa
  107.     var response ResponseAllData
  108.     db := dbConn()
  109.     defer db.Close()
  110.     params := mux.Vars(r)
  111.     query := fmt.Sprintf("SELECT * FROM mahasiswa WHERE nama LIKE '%s%%'", params["keyword"])
  112.     rows, err := db.Query(query)
  113.     if err != nil {
  114.         log.Print(err.Error())
  115.     }
  116.     for rows.Next() {
  117.         if err := rows.Scan(&mahasiswa.Id, &mahasiswa.Npm, &mahasiswa.Nama, &mahasiswa.Kelas, &mahasiswa.Profile); err != nil {
  118.             log.Print(err.Error())
  119.         }
  120.         mhs = append(mhs, mahasiswa)
  121.     }
  122.     response.Status = true
  123.     response.Data = mhs
  124.     json.NewEncoder(w).Encode(response)
  125.     return
  126. }
  127. func createMahasiswa(w http.ResponseWriter, r *http.Request) {
  128.     w.Header().Set("Content-type", "application/json")
  129.     var response ResponseMessage
  130.     db := dbConn()
  131.     defer db.Close()
  132.     err := r.ParseForm()
  133.     if err != nil {
  134.         log.Print(err.Error())
  135.     }
  136.     npm := r.Form.Get("npm")
  137.     nama := r.Form.Get("nama")
  138.     kelas := r.Form.Get("kelas")
  139.     profile := "gambar1.jpg"
  140.     rows, err := db.Prepare("INSERT INTO mahasiswa(npm, nama, kelas, profile) VALUES(?, ?, ?, ?)")
  141.     if err != nil {
  142.         log.Print(err.Error())
  143.     }
  144.     rows.Exec(npm, nama, kelas, profile)
  145.     response.Status = true
  146.     response.Message = "Mahasiswa berhasil ditambahkan"
  147.     log.Print(response.Message)
  148.     json.NewEncoder(w).Encode(response)
  149. }
  150. func updateMahasiswa(w http.ResponseWriter, r *http.Request) {
  151.     w.Header().Set("Content-type", "application/json")
  152.     var response ResponseMessage
  153.     var responseErr ResponseError
  154.     var mahasiswa Mahasiswa
  155.     db := dbConn()
  156.     defer db.Close()
  157.     err := r.ParseForm()
  158.     if err != nil {
  159.         log.Print(err.Error())
  160.     }
  161.     id := r.Form.Get("id")
  162.     npm := r.Form.Get("npm")
  163.     nama := r.Form.Get("nama")
  164.     kelas := r.Form.Get("kelas")
  165.     rows := db.QueryRow("SELECT id FROM mahasiswa WHERE id=?", id)
  166.     if err := rows.Scan(&mahasiswa.Id); err != nil && err == sql.ErrNoRows {
  167.         responseErr.Status = false
  168.         responseErr.Error = "Mahasiswa tidak ditemukan"
  169.         w.WriteHeader(http.StatusNotFound)
  170.         json.NewEncoder(w).Encode(responseErr)
  171.         return
  172.     }
  173.     update, err := db.Prepare("UPDATE mahasiswa SET npm=?, nama=?, kelas=? WHERE id=?")
  174.     if err != nil {
  175.         log.Print(err.Error())
  176.     }
  177.     update.Exec(npm, nama, kelas, id)
  178.     response.Status = true
  179.     response.Message = "Data mahasiswa berhasil diubah"
  180.     log.Print(response.Message)
  181.     json.NewEncoder(w).Encode(response)
  182.     return
  183. }
  184. func deleteMahasiswa(w http.ResponseWriter, r *http.Request) {
  185.     w.Header().Set("Content-type", "application/json")
  186.     var mahasiswa Mahasiswa
  187.     var response ResponseMessage
  188.     var responseErr ResponseError
  189.     db := dbConn()
  190.     defer db.Close()
  191.     params := mux.Vars(r)
  192.     rows := db.QueryRow("SELECT id FROM mahasiswa WHERE id=?", params["id"])
  193.     if err := rows.Scan(&mahasiswa.Id); err != nil && err == sql.ErrNoRows {
  194.         responseErr.Status = false
  195.         responseErr.Error = "Mahasiswa tidak ditemukan"
  196.         w.WriteHeader(http.StatusNotFound)
  197.         json.NewEncoder(w).Encode(responseErr)
  198.         return
  199.     }
  200.     delete, err := db.Prepare("DELETE FROM mahasiswa WHERE id=?")
  201.     if err != nil {
  202.         log.Print(err.Error())
  203.     }
  204.     delete.Exec(params["id"])
  205.     response.Status = true
  206.     response.Message = "Data mahasiswa berhasil dihapus"
  207.     log.Print(response.Message)
  208.     json.NewEncoder(w).Encode(response)
  209.     return
  210. }
  211. func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  212.     path := filepath.Join(h.staticPath, r.URL.Path)
  213.     _, err := os.Stat(path)
  214.     if os.IsNotExist(err) {
  215.         http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath))
  216.         return
  217.     } else if err != nil {
  218.         http.Error(w, err.Error(), http.StatusInternalServerError)
  219.         return
  220.     }
  221.     http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r)
  222. }
  223. func main() {
  224.     r := mux.NewRouter().StrictSlash(true)
  225.     mime.AddExtensionType(".js", "application/javascript")
  226.     r.HandleFunc("/api/mahasiswa", getAllMahasiswa).Methods("GET")
  227.     r.HandleFunc("/api/mahasiswa/{id}", getMahasiswa).Methods("GET")
  228.     r.HandleFunc("/api/mahasiswa", createMahasiswa).Methods("POST")
  229.     r.HandleFunc("/api/mahasiswa", updateMahasiswa).Methods("PUT")
  230.     r.HandleFunc("/api/mahasiswa/{id}", deleteMahasiswa).Methods("DELETE")
  231.     r.HandleFunc("/mahasiswa/search/{keyword}", getMahasiswaByName).Methods("GET")
  232.     spa := spaHandler{staticPath: "polymer", indexPath: "index.html"}
  233.     r.PathPrefix("/").Handler(spa)
  234.     srv := &http.Server{
  235.         Handler:      r,
  236.         Addr:         "localhost:9000",
  237.         WriteTimeout: 15 * time.Second,
  238.         ReadTimeout:  15 * time.Second,
  239.     }
  240.     log.Print("Server berjalan di http://localhost:9000")
  241.     srv.ListenAndServe()
  242. }
  243.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement