Cara membuat Http Server di Golang part 2
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Product struct {
Name string `json:"name"`
Price int `json:"price"`
Stock int `json:"stock"`
}
var products []Product
func main() {
http.HandleFunc("/product", GetProductsHandler)
http.HandleFunc("/product/create", CreateProductHandler)
http.HandleFunc("/product/update", UpdateProductHandler)
http.HandleFunc("/product/delete", DeleteProductHandler)
http.ListenAndServe(":8080", nil)
}
func GetProductsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
// Handle GET request, return list of products
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(products)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method not allowed")
}
}
func CreateProductHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
// Handle POST request, parse request body and validate
var product Product
err := json.NewDecoder(r.Body).Decode(&product)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid request body")
return
}
// Basic validation
if product.Name == "" || product.Price <= 0 || product.Stock < 0 {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid product data")
return
}
// Save the product to the list
products = append(products, product)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(product)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method not allowed")
}
}
func UpdateProductHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "PUT" {
// Handle PUT request, parse request body and validate
var updatedProduct Product
err := json.NewDecoder(r.Body).Decode(&updatedProduct)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Invalid request body")
return
}
// Find and update the product in the products list
var found bool
for i, p := range products {
if p.Name == updatedProduct.Name {
products[i] = updatedProduct
found = true
break
}
}
if !found {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Product not found")
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(updatedProduct)
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method not allowed")
}
}
func DeleteProductHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "DELETE" {
// Parse product name from URL query parameter
productName := r.URL.Query().Get("name")
if productName == "" {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "Product name is required")
return
}
// Find and remove the product from the products list
var found bool
for i, p := range products {
if p.Name == productName {
products = append(products[:i], products[i+1:]...)
found = true
break
}
}
if !found {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Product not found")
return
}
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Product deleted successfully")
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
fmt.Fprintf(w, "Method not allowed")
}
}Penjelasan:
Langkah 1: Install Library helmet, xss-mw, dan cors
helmet, xss-mw, dan corsLangkah 2: Lengkapi main.go dengan Middleware yang Dibutuhkan
main.go dengan Middleware yang DibutuhkanLast updated