Artikel ini membawa kamu dari nol sampai punya web server Go yang bisa dibuka di browser — dikerjakan di VS Code. Bukan hanya teori, setiap bagian punya kode yang bisa langsung dicoba.
Setup VS Code untuk Go
VS Code adalah editor yang paling nyaman untuk Go berkat extension resmi dari Google yang memberikan autocomplete, error checking, debugger, dan test runner — semua terintegrasi.
Langkah Setup:
① Install VS Code
Download dari code.visualstudio.com → install sesuai OS.
② Install Extension: Go (by Google)
Go
oleh Go Team at Google · Extension resmi
Autocomplete, error checking, go-to-definition, debugger, dan test runner terintegrasi untuk Go.
📌 Tekan Ctrl+Shift+X → cari "Go" → pilih yang by Go Team at Google → Install.
⚠️ Setelah install, VS Code akan menampilkan notifikasi "The 'gopls' language server is not installed". Klik Install atau Install All untuk menginstall semua Go tools yang dibutuhkan.
③ Cara Buka Terminal di VS Code
Tekan Ctrl + ` atau klik menu Terminal → New Terminal. Semua command go run, go build, dan go test dijalankan dari sini.
📋 Progress Belajarmu
Centang tiap langkah yang sudah selesai. Progress tersimpan otomatis!
1. Install Go
Download installer dari go.dev/dl sesuai OS kamu (Windows/Mac/Linux), install, lalu buka terminal dan verifikasi:
go version
# Output: go version go1.22.0 windows/amd64
2. Buat Project Baru
# Buat folder project
mkdir belajar-go
cd belajar-go
# Inisialisasi Go module (seperti package.json di Node / composer.json di PHP)
go mod init belajar-go
Sekarang kamu punya file go.mod di folder tersebut. Struktur project akan seperti ini:
belajar-go/
├── go.mod
└── main.go ← file utama yang akan kita buat
3. Hello World — Pertama Kali Running
Buat file main.go, isi dengan kode berikut:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Jalankan:
go run main.go
# Output: Hello, World!
go run main.go — jalankan langsung tanpa compile ke file binarygo build -o app main.go — compile jadi file executable yang bisa didistribusikan
4. Sintaks Dasar
Variabel
// Short declaration — paling sering dipakai
nama := "Budi"
umur := 25
tinggi := 175.5
aktif := true
// Deklarasi eksplisit
var kota string = "Jakarta"
// Konstanta
const MaxUser = 100
const AppName = "BelajarGo"
If / Else
nilai := 85
if nilai >= 90 {
fmt.Println("A")
} else if nilai >= 75 {
fmt.Println("B")
} else {
fmt.Println("C")
}
For Loop (satu-satunya loop di Go)
// Loop klasik
for i := 0; i < 5; i++ {
fmt.Println(i)
}
// Seperti while
x := 1
for x <= 10 {
x++
}
// Range — loop slice/map
buah := []string{"apel", "mangga", "jeruk"}
for i, nama := range buah {
fmt.Printf("%d: %s\n", i, nama)
}
Function
// Go bisa return lebih dari satu nilai — ini fitur khas Go
func bagi(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("tidak bisa bagi dengan nol")
}
return a / b, nil
}
hasil, err := bagi(10, 3)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("%.2f\n", hasil) // 3.33
}
Slice & Map
// Slice (array dinamis)
angka := []int{1, 2, 3}
angka = append(angka, 4, 5)
fmt.Println(len(angka)) // 5
// Map (key-value)
profil := map[string]string{
"nama": "Budi",
"kota": "Jakarta",
}
profil["email"] = "budi@email.com"
delete(profil, "kota")
fmt.Println(profil["nama"])
Struct
type Produk struct {
Nama string
Harga int
Stok int
}
// Method pada struct
func (p Produk) Info() string {
return fmt.Sprintf("%s — Rp%d (stok: %d)", p.Nama, p.Harga, p.Stok)
}
laptop := Produk{Nama: "Laptop", Harga: 15000000, Stok: 5}
fmt.Println(laptop.Info())
5. Web Server di Browser — Tanpa Library Eksternal
Go punya package net/http built-in yang sudah cukup untuk membuat web server. Tidak perlu install apapun.
Update main.go dengan kode berikut:
package main
import (
"fmt"
"net/http"
)
func halaman(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Halo dari Go!</h1><p>URL: %s</p>", r.URL.Path)
}
func main() {
http.HandleFunc("/", halaman)
fmt.Println("Server berjalan di http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
Jalankan dan buka browser:
go run main.go
# Server berjalan di http://localhost:8080
Buka http://localhost:8080 di browser — kamu akan melihat halaman dengan tulisan "Halo dari Go!".
6. Web Server Lengkap dengan HTML Template & Data Dinamis
Sekarang kita buat versi yang lebih nyata: web server dengan HTML template, data struct, dan multiple route.
Buat dua file:
belajar-go/
├── go.mod
├── main.go
└── templates/
└── index.html
main.go
package main
import (
"html/template"
"net/http"
"fmt"
)
// Struct untuk data produk
type Produk struct {
Nama string
Harga int
Stok int
}
// Data yang akan ditampilkan di web
type PageData struct {
Judul string
Produk []Produk
}
func halamanUtama(w http.ResponseWriter, r *http.Request) {
// Parse template HTML
tmpl := template.Must(template.ParseFiles("templates/index.html"))
// Siapkan data
data := PageData{
Judul: "Toko Online Go",
Produk: []Produk{
{"Laptop Gaming", 15000000, 3},
{"Mechanical Keyboard", 850000, 12},
{"Monitor 27 inch", 4500000, 7},
{"Webcam HD", 450000, 20},
},
}
// Render template dengan data
tmpl.Execute(w, data)
}
func halamanTentang(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Tentang Kami</h1><p>Dibuat dengan Go!</p><a href='/'>Kembali</a>")
}
func main() {
// Daftarkan routes
http.HandleFunc("/", halamanUtama)
http.HandleFunc("/tentang", halamanTentang)
port := ":8080"
fmt.Println("Server berjalan di http://localhost" + port)
fmt.Println("Tekan Ctrl+C untuk berhenti")
// Start server
if err := http.ListenAndServe(port, nil); err != nil {
fmt.Println("Error:", err)
}
}
templates/index.html
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>{{.Judul}}</title>
<style>
body { font-family: sans-serif; max-width: 800px; margin: 40px auto; padding: 0 20px; }
h1 { color: #0f766e; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th { background: #0f766e; color: white; padding: 10px; text-align: left; }
td { padding: 10px; border-bottom: 1px solid #e2e8f0; }
tr:hover { background: #f0fdfa; }
</style>
</head>
<body>
<h1>{{.Judul}}</h1>
<a href="/tentang">Tentang Kami</a>
<table>
<thead>
<tr>
<th>Produk</th>
<th>Harga</th>
<th>Stok</th>
</tr>
</thead>
<tbody>
{{range .Produk}}
<tr>
<td>{{.Nama}}</td>
<td>Rp{{.Harga}}</td>
<td>{{.Stok}}</td>
</tr>
{{end}}
</tbody>
</table>
<p style="color:#94a3b8;margin-top:30px">Total produk: {{len .Produk}}</p>
</body>
</html>
Jalankan:
go run main.go
# Server berjalan di http://localhost:8080
Buka http://localhost:8080 — kamu akan melihat halaman tabel produk yang dibuat dari data Go struct secara dinamis.
7. Build Jadi File Executable
Kalau mau deploy ke server atau bagikan ke orang lain tanpa perlu install Go:
# Build untuk OS saat ini
go build -o app main.go
# Jalankan binary-nya langsung
./app # Linux/Mac
app.exe # Windows
# Build untuk OS lain (cross-compile)
GOOS=linux GOARCH=amd64 go build -o app-linux main.go
GOOS=windows GOARCH=amd64 go build -o app.exe main.go
GOOS=darwin GOARCH=amd64 go build -o app-mac main.go
go run main.go | Jalankan langsung (development) |
go build -o app | Compile jadi executable |
go mod init nama | Buat project baru |
go get package | Install dependency |
go mod tidy | Bersihkan dependency yang tidak dipakai |
go test ./... | Jalankan semua unit test |
Komentar 0