ProgramGuru

Introduction to Web Development in Go

Start with Introduction to Web Development in Go

In this lesson, explore introduction to web development in go through one small Go program, and connect its output to the language rules behind it.

What you’ll learn

  • Explain the main purpose of introduction to web development in go.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Go’s net/http package supplies HTTP clients, servers, requests, responses and routing. A handler receives a request and writes a response.

The first example invokes a handler in memory with httptest, so it needs no open port. A real server places the same handler behind a network listener.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for webA handler is the request-to-response boundary.HTTP requestStep 1Go handlerStep 2ResponseWriterStep 3HTTP responseStep 4A handler is the request-to-response boundary.
A handler is the request-to-response boundary.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func main() {
	handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome to Go") })
	request := httptest.NewRequest(http.MethodGet, "/", nil)
	recorder := httptest.NewRecorder()
	handler.ServeHTTP(recorder, request)
	fmt.Println("Response:", recorder.Body.String())
}

Output

Response: Welcome to Go

Trace what the program does

The in-memory request is passed to a handler, which writes a message. The recorder captures that message without a network socket.

Avoid common mistakes

  • A handler’s response writer is not the same thing as a database connection.
  • Use network request tests as well as handler tests when checking real deployments.

Try it yourself

Change the handler to return your own greeting and test the result with httptest.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What is the role of an HTTP handler?
Choose one answer. You can try again.

Answer and explanation

Process a request and write its response

Correct. The in-memory request is passed to a handler, which writes a message.

What you should remember

You have practiced Introduction to Web Development in Go in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: HTTP Fundamentals →