Section 8 of 12
HTTP Servers & Clients
Build web servers and make HTTP requests
Course Progress
Section 8 of 1267% complete
Tutorials
HTTP Servers
Go's net/http package makes it easy to build web servers with minimal overhead.
Code Examples
Basic HTTP Servergo
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!\n", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", helloHandler)
fmt.Println("Server starting on :8080")
http.ListenAndServe(":8080", nil)
}Multiple Routesgo
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type Response struct {
Message string `json:"message"`
Status string `json:"status"`
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprintf(w, "<h1>Welcome</h1>")
}
func apiHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
resp := Response{Message: "Hello API", Status: "ok"}
json.NewEncoder(w).Encode(resp)
}
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/api", apiHandler)
http.ListenAndServe(":8080", nil)
}HTTP Clients
Make HTTP requests from Go to consume APIs and services.
Code Examples
HTTP Requestsgo
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// GET request
resp, err := http.Get("https://api.github.com/users/golang")
if err != nil {
fmt.Println(err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
// POST request
resp, _ = http.Post("https://api.example.com/data",
"application/json",
strings.NewReader(`{"key":"value"}`))
defer resp.Body.Close()
}Exercises
REST API Server
Create a simple REST API server with GET and POST endpoints
INTERMEDIATEStarter Code:
package main
import (
"fmt"
"net/http"
"encoding/json"
)
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
// TODO: Create REST API endpoints
}Hands-on Project
Todo API
Build a complete Todo REST API with CRUD operations
ADVANCED
Learning Objectives
- >Build REST APIs
- >Handle JSON
- >Implement CRUD operations
Project Tips
- > Start by understanding the requirements
- > Break the project into smaller tasks
- > Test your code frequently as you build
- > Add error handling throughout your code
- > Consider edge cases and validate inputs
- > Document your code with comments