Ang Go net/http package kay built-in HTTP client para mag-request sa web servers. Anhi nga chapter: GET ug POST requests, JSON, file uploads, custom headers, ug pag-handle ug responses. Sulit jud.
Ang http.Client type nag-handle ug HTTP requests ug responses. Para simple use, ang zero-value client (&http.Client{}) kay ok na. Pero for production, dapat mag-configure ka ug timeouts ug transports — ayawg pabayaan:
client := &http.Client{
Timeout: 10 * time.Second,
}
// Convenience functions also use the default client:
// http.Get(url), http.Post(url, contentType, body), http.Head(url)
Gamit ug http.Get para simple GET requests. Importante: always close ang response body with defer:
resp, err := http.Get("https://api.example.com/users")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Status:", resp.Status)
fmt.Println("Body:", string(body))
Goal: Maghimo ug GET request sa public API ug i-print ang response status ug parte sa body.
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
resp, err := http.Get("https://jsonplaceholder.typicode.com/posts/1")
if err != nil {
fmt.Println("Error:", err)
return
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println("Status:", resp.StatusCode)
fmt.Println("Body:", string(body))
}
Ang APIs kasagarang nag-return ug JSON. Gamit ug json.Unmarshal or json.Decoder para i-parse ang response body diretso — no extra steps:
resp, _ := http.Get("https://api.example.com/users/1")
defer resp.Body.Close()
var user User
json.NewDecoder(resp.Body).Decode(&user)
fmt.Println(user.Name)
Goal: Kuha ug todo item gikan sa JSONPlaceholder ug i-unmarshal into Go struct.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Todo struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
Completed bool `json:"completed"`
}
func main() {
resp, _ := http.Get("https://jsonplaceholder.typicode.com/todos/1")
defer resp.Body.Close()
var todo Todo
json.NewDecoder(resp.Body).Decode(&todo)
fmt.Printf("%+v\n", todo)
}
Goal: Kuha tanang posts para sa user ID 1, i-filter ang even IDs, ug i-print ang titles.
package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Post struct {
UserID int `json:"userId"`
ID int `json:"id"`
Title string `json:"title"`
}
func main() {
resp, _ := http.Get("https://jsonplaceholder.typicode.com/posts?userId=1")
defer resp.Body.Close()
var posts []Post
json.NewDecoder(resp.Body).Decode(&posts)
for _, p := range posts {
if p.ID%2 == 0 {
fmt.Println(p.ID, p.Title)
}
}
}
Gamit ug http.Post or http.PostForm para magpadala ug data sa server:
// JSON body
jsonData := []byte(`{"title":"foo","body":"bar","userId":1}`)
resp, _ := http.Post(
"https://jsonplaceholder.typicode.com/posts",
"application/json",
bytes.NewReader(jsonData),
)
defer resp.Body.Close()
// Form data
resp, _ = http.PostForm("https://example.com/login",
url.Values{"username": {"alice"}, "password": {"secret"}},
)
Goal: Paghimo ug bag-o nga post via POST request ug i-print ang response.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Post struct {
Title string `json:"title"`
Body string `json:"body"`
UserID int `json:"userId"`
}
func main() {
p := Post{"My Title", "My Content", 1}
data, _ := json.Marshal(p)
resp, _ := http.Post(
"https://jsonplaceholder.typicode.com/posts",
"application/json",
bytes.NewReader(data),
)
defer resp.Body.Close()
var created Post
json.NewDecoder(resp.Body).Decode(&created)
fmt.Printf("Created: %+v\n", created)
}
Gamit ug multipart.Writer para mag-upload ug files sa server:
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
// Add a file
fw, _ := w.CreateFormFile("file", "photo.jpg")
file, _ := os.Open("photo.jpg")
io.Copy(fw, file)
file.Close()
w.Close()
resp, _ := http.Post(
"https://example.com/upload",
w.FormDataContentType(),
&buf,
)
Goal: Maghimo ug simple text file sa memory ug i-upload as multipart form.
package main
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
)
func main() {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
fw, _ := w.CreateFormFile("file", "note.txt")
fw.Write([]byte("Hello, this is a test file"))
w.Close()
resp, _ := http.Post(
"https://httpbin.org/post",
w.FormDataContentType(),
&buf,
)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Paghimo ug request gamit http.NewRequest para mag-set ug custom headers (auth tokens, user-agent, etc.):
data := []byte(`{"query":"golang"}`)
req, _ := http.NewRequest("POST", "https://api.example.com/search",
bytes.NewReader(data))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer my-token")
req.Header.Set("User-Agent", "MyApp/1.0")
client := &http.Client{}
resp, err := client.Do(req)
Goal: Magpadala ug GET request nga naay custom User-Agent header ug i-print ang response.
package main
import (
"fmt"
"io"
"net/http"
)
func main() {
req, _ := http.NewRequest("GET", "https://httpbin.org/headers", nil)
req.Header.Set("User-Agent", "GoTutorial/1.0")
req.Header.Set("X-Custom", "myvalue")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}
Goal: Mag-POST ug comment, dayon GET ang list ug i-verify kung nag-appear ba ang bag-o nga comment.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type Comment struct {
PostID int `json:"postId"`
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Body string `json:"body"`
}
func main() {
c := Comment{PostID: 1, Name: "Alice", Email: "a@b.com", Body: "Great post!"}
data, _ := json.Marshal(c)
resp, _ := http.Post(
"https://jsonplaceholder.typicode.com/comments",
"application/json", bytes.NewReader(data),
)
resp.Body.Close()
resp, _ = http.Get("https://jsonplaceholder.typicode.com/comments?postId=1")
defer resp.Body.Close()
var comments []Comment
json.NewDecoder(resp.Body).Decode(&comments)
fmt.Printf("Found %d comments for post 1\n", len(comments))
}
http.Get ug http.Post para simple requestshttp.NewRequest para full control (custom headers, methods, etc.)resp.Body with defer — di mag-leak ang resourcesjson.NewDecoder para i-parse ang JSON responses diretsomultipart.Writer para file uploadshttp.Client na may timeouts para production