CSE224 - HTTP server
Required library packages
Http package
net/http: A standard library package in Go to create and handle web-based communication using the HTTP protocol.
http.HandleFunc(path, handler): When someone visits path, run the handler function. e.g.,http.HandleFunc("/", homeHandler)http.ListenAndServe(addr, nil): Starts the server and listens on a specific address/port. e.g.,http.ListenAndServe(":8080", nil), Listen for HTTP requests on port 8080.func(w http.ResponseWriter, r *http.Request): This is what handler functions look like.
func greetHandler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name") // Reads a query parameter from the URL
if name == "" {
name = "Guest"
}
fmt.Fprintf(w, "Hello, %s!", name)
}
func main() {
http.HandleFunc("/", greetoHandler)
http.ListenAndServe(":8080", nil)
}Then visit http://localhost:8080/?name=Alice, and will output: Hello, Alice!
r.URL.Query().Get("id"): Reads a query parameter from the URL, like/student?id=Alicer.ParseForm(): Used for reading form data submitted via POST.name := r.FormValue("student_name"): Access form values, gives you the first value for that key.r.Form["key"]: gives you all values as a slice ([]string)http.Redirect(...): Redirects the browser to another URL after a POST request.
html/template package
html/template is a Go standard library package that helps you create HTML pages with dynamic content.
- Define HTML Template
<h2>Student Name: {{.Name}}</h2>
<h2>Grade: {{.Grade}}</h2>- Define a go struct
type GradeInfo struct {
Name string
Grade string
}- Fill the template
tmpl := template.Must(template.ParseFiles("gradeinfo.html"))
student := GradeInfo{Name: "Alice", Grade: "A+"}
tmpl.Execute(w, student)tmpl.Execute(w, students) use template for index.html, fill data from student, dynamically generate a HTML page, and finally write the page to w.
CSE224 - HTTP server
http://example.com/2025/05/21/CSE224/http-server/