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.
1 |
|
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=Alice
r.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
1
2
3<!-- gradeinfo.html -->
<h2>Student Name: {{.Name}}</h2>
<h2>Grade: {{.Grade}}</h2>Define a go struct
1
2
3
4type GradeInfo struct {
Name string
Grade string
}Fill the template
1
2
3
4tmpl := 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
https://thiefcat.github.io/2025/05/21/CSE224/http-server/