← Danh sách bài học
Bài 18/20
🌐 Bài 18: HTTP Server
🎯 Mục tiêu:
- Tạo HTTP server đơn giản
- Viết handlers cho routes
- Đọc query params và form data
- Xử lý các HTTP methods
1. Hello World Server
package main
import (
"fmt"
"net/http"
)
func main() {
// Handler cho route "/"
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
fmt.Println("Server running at http://localhost:8080")
http.ListenAndServe(":8080", nil)
}
💡 Chạy:
go run main.go rồi mở browser http://localhost:8080
2. Multiple Routes
func homeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Trang chủ")
}
func aboutHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Giới thiệu")
}
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/about", aboutHandler)
http.ListenAndServe(":8080", nil)
}
3. Đọc Query Parameters
// URL: /greet?name=Minh&age=25
func greetHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
age := r.URL.Query().Get("age")
if name == "" {
name = "Guest"
}
fmt.Fprintf(w, "Xin chào %s, %s tuổi!", name, age)
}
4. Xử Lý HTTP Methods
func userHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
fmt.Fprintf(w, "Lấy danh sách users")
case "POST":
fmt.Fprintf(w, "Tạo user mới")
case "PUT":
fmt.Fprintf(w, "Cập nhật user")
case "DELETE":
fmt.Fprintf(w, "Xóa user")
default:
http.Error(w, "Method không hỗ trợ",
http.StatusMethodNotAllowed)
}
}
5. Đọc Request Body
import (
"io"
"net/http"
)
func createHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Chỉ chấp nhận POST",
http.StatusMethodNotAllowed)
return
}
// Đọc body
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Lỗi đọc body",
http.StatusBadRequest)
return
}
defer r.Body.Close()
fmt.Fprintf(w, "Nhận được: %s", string(body))
}
6. Static Files
func main() {
// Serve files từ thư mục "static"
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
http.HandleFunc("/", homeHandler)
http.ListenAndServe(":8080", nil)
}
📝 Tóm Tắt
http.HandleFunc(path, handler)- đăng ký routehttp.ListenAndServe(":port", nil)- start serverr.URL.Query().Get("param")- lấy query paramr.Method- kiểm tra HTTP methodio.ReadAll(r.Body)- đọc request body