Chapter 14: Using the Go HTTP Client

Introduksyon

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.

The Go HTTP Client and Its Uses

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)

Sending a Request to a Server

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))

Exercise 14.01: Sending a Get Request to a Web Server Using the Go HTTP Client

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))
}

Structured Data

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)

Exercise 14.02: Using the HTTP Client with Structured Data

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)
}

Activity 14.01: Requesting Data from a Web Server and Processing the Response

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)
        }
    }
}

Sending Data to a Server

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"}},
)

Exercise 14.03: Sending a Post Request to a Web Server Using the Go HTTP Client

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)
}

Uploading Files in a Post Request

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,
)

Exercise 14.04: Uploading a File to a Web Server via a Post Request

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))
}

Custom Request Headers

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)

Exercise 14.05: Using Custom Headers and Options with the Go HTTP Client

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))
}

Activity 14.02: Sending Data to a Web Server and Checking Whether the Data Was Received Using POST and GET

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))
}

Summary