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
2
3
4
5
6
7
8
9
10
11
12
13
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=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.

  1. Define HTML Template

    1
    2
    3
    <!-- gradeinfo.html -->
    <h2>Student Name: {{.Name}}</h2>
    <h2>Grade: {{.Grade}}</h2>
  2. Define a go struct

    1
    2
    3
    4
    type GradeInfo struct {
    Name string
    Grade string
    }
  3. Fill the template

    1
    2
    3
    4
    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
https://thiefcat.github.io/2025/05/21/CSE224/http-server/
Author
小贼猫
Posted on
May 21, 2025
Licensed under