56

Hello world HTTP server example

 3 years ago
source link: https://yourbasic.org/golang/http-server-example/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Hello world HTTP server example

yourbasic.org/golang

A basic web server

If you access the URL http://localhost:8080/world on a machine where the program below is running, you will be greeted by this page.

Web browser localhost:8080
package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", HelloServer)
    http.ListenAndServe(":8080", nil)
}

func HelloServer(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
  • The call to http.HandleFunc tells the net.http package to handle all requests to the web root with the HelloServer function.
  • The call to http.ListenAndServe tells the server to listen on the TCP network address :8080. This function blocks until the program is terminated.
  • Writing to an http.ResponseWriter sends data to the HTTP client.
  • An http.Request is a data structure that represents a client HTTP request.
  • r.URL.Path is the path component of the requested URL. In this case, "/world" is the path component of "http://localhost:8080/world".

Further reading: a complete wiki

The Writing Web Applications tutorial shows how to extend this small example into a complete wiki.

The tutorial covers how to

  • create a data structure with load and save methods,
  • use the net/http package to build web applications,
  • use the html/template package to process HTML templates,
  • use the regexp package to validate user input.

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK