Skip to content

Commit 3dc2413

Browse files
rscgopherbot
authored andcommitted
helloserver: add basic hello world web server
We want to revive golang.org/x/example as a test case for an experiment with a 'gonew' command. This CL adds a basic "hello, world" web server as golang.org/x/example/helloserver. Change-Id: Icf76c756f7b256285d4c5e6a33655996597eb2da Reviewed-on: https://go-review.googlesource.com/c/example/+/513997 Auto-Submit: Russ Cox <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Run-TryBot: Russ Cox <[email protected]> Reviewed-by: Cameron Balahan <[email protected]>
1 parent 1bcfdd0 commit 3dc2413

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

helloserver/go.mod

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
module golang.org/x/example/helloserver
2+
3+
go 1.19
4+

helloserver/server.go

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// Copyright 2023 The Go Authors. All rights reserved.
2+
// Use of this source code is governed by a BSD-style
3+
// license that can be found in the LICENSE file.
4+
5+
// Hello is a simple hello, world demonstration web server.
6+
//
7+
// It serves version information on /version and answers
8+
// any other request like /name by saying "Hello, name!".
9+
//
10+
// See golang.org/x/example/outyet for a more sophisticated server.
11+
package main
12+
13+
import (
14+
"flag"
15+
"fmt"
16+
"html"
17+
"log"
18+
"net/http"
19+
"os"
20+
"runtime/debug"
21+
"strings"
22+
)
23+
24+
func usage() {
25+
fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n")
26+
flag.PrintDefaults()
27+
os.Exit(2)
28+
}
29+
30+
var (
31+
greeting = flag.String("g", "Hello", "Greet with `greeting`")
32+
addr = flag.String("addr", "localhost:8080", "address to serve")
33+
)
34+
35+
func main() {
36+
// Parse flags.
37+
flag.Usage = usage
38+
flag.Parse()
39+
40+
// Parse and validate arguments (none).
41+
args := flag.Args()
42+
if len(args) != 0 {
43+
usage()
44+
}
45+
46+
// Register handlers.
47+
// All requests not otherwise mapped with go to greet.
48+
// /version is mapped specifically to version.
49+
http.HandleFunc("/", greet)
50+
http.HandleFunc("/version", version)
51+
52+
log.Printf("serving http://%s\n", *addr)
53+
log.Fatal(http.ListenAndServe(*addr, nil))
54+
}
55+
56+
func version(w http.ResponseWriter, r *http.Request) {
57+
info, ok := debug.ReadBuildInfo()
58+
if !ok {
59+
http.Error(w, "no build information available", 500)
60+
return
61+
}
62+
63+
fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n")
64+
fmt.Fprintf(w, "%s\n", html.EscapeString(info.String()))
65+
}
66+
67+
func greet(w http.ResponseWriter, r *http.Request) {
68+
name := strings.Trim(r.URL.Path, "/")
69+
if name == "" {
70+
name = "Gopher"
71+
}
72+
73+
fmt.Fprintf(w, "<!DOCTYPE html>\n")
74+
fmt.Fprintf(w, "Hello, %s!\n", html.EscapeString(name))
75+
}

0 commit comments

Comments
 (0)