{{.Title}}
{{.Content}}
net/http
Package in Go
http.ListenAndServe
to start an HTTP server on a specific address and port
http.Handler
interface has one method:
ServeHTTP
package main
import (
"fmt"
"net/http"
)
// helloHandler responds to an HTTP request with "Hello, World!"
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, World!")
}
func main() {
// Convert the helloHandler function to a type that implements http.Handler
http.HandleFunc("/", helloHandler)
// Start the server and listen on port 8080
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
http.HandleFunc
takes URL path and function with
func(http.ResponseWriter, *http.Request)
signature
http.ResponseWriter
to write response to the client
http.ResponseWriter
is an interface for assembling HTTP response
*http.Request
type represents client's request
http.HandleFunc
associates URL pattern with function
net/http
is part of Go standard library
net/http
package first
net/http
package for HTTP implementations
http.ListenAndServe
Importing net/http Package
import (
"net/http"
)
Defining the Handler Function
The handler function receives two parameters:
w
: http.ResponseWriter - to send responses
r
: *http.Request - holds incoming request details
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Hello, this is a GET request!"))
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte("Method Not Allowed"))
}
}
Attaching the Handler Function
http.HandleFunc("/", handler)
Starting the HTTP Server
http.ListenAndServe(":8080", nil)
Pre-requisite Knowledge
net/http
package in Go
Key Considerations
The Model-View-Controller (MVC) design pattern is a way to organize code and separate concerns in web applications. It divides an application into three interconnected components, helping developers to manage complexity and scalability.
Let's look at an example of implementing the MVC pattern in Go for a simple blog application:
Represents a blog post.
package models
// BlogPost models a blog post for the application
type BlogPost struct {
ID int
Title string
Content string
}
// FetchAllPosts would fetch all blog posts from the database
func FetchAllPosts() ([]BlogPost, error) {
// logic to retrieve all posts from the database
}
// FetchPostByID would fetch a single post given its ID
func FetchPostByID(id int) (BlogPost, error) {
// logic to retrieve a post by ID from the database
}
Presents the data in HTML format.
{{range .}}
{{.Title}}
{{.Content}}
{{else}}
No posts to show.
{{end}}
{{.Title}}
{{.Content}}
Processes requests, interacts with the Model, and selects the View.
package controllers
import (
"net/http"
"html/template"
"path/filepath"
"myapp/models"
)
func ListBlogPosts(w http.ResponseWriter, r *http.Request) {
posts, err := models.FetchAllPosts()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl := template.Must(template.ParseFiles(filepath.Join("view", "blog", "index.html")))
tmpl.Execute(w, posts)
}
func GetBlogPost(w http.ResponseWriter, r *http.Request) {
// here we'd parse the ID from the request, e.g., using a router
post, err := models.FetchPostByID(someID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpl := template.Must(template.ParseFiles(filepath.Join("view", "blog", "show.html")))
tmpl.Execute(w, post)
}
Sets up the server and routes the requests to appropriate controllers.
package main
import (
"net/http"
"myapp/controllers"
)
func main() {
http.HandleFunc("/", controllers.ListBlogPosts)
http.HandleFunc("/post/", controllers.GetBlogPost)
http.ListenAndServe(":8080", nil)
}
In this scenario, for every request, the Controller decides which Model method should be
Which of the following statements regarding the http.ListenAndServe function in Go is true?
In the Model-View-Controller (MVC) pattern implemented in Go, what is the primary responsibility of the Controller?