forked from golang/example
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.go
More file actions
91 lines (76 loc) · 2.12 KB
/
Copy pathserver.go
File metadata and controls
91 lines (76 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Hello is a simple hello, world demonstration web server.
//
// It serves version information on /version and answers
// any other request like /name by saying "Hello, name!".
//
// See golang.org/x/example/outyet for a more sophisticated server.
package main
import (
"flag"
"fmt"
"html"
"log"
"net/http"
"os"
"runtime/debug"
"strings"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: helloserver [options]\n")
flag.PrintDefaults()
os.Exit(2)
}
var (
greeting = flag.String("g", "Hello", "Greet with `greeting`")
addr = flag.String("addr", "localhost:8080", "address to serve")
)
func main() {
// Parse flags.
flag.Usage = usage
flag.Parse()
// Parse and validate arguments (none).
args := flag.Args()
if len(args) != 0 {
usage()
}
// Register handlers.
// All requests not otherwise mapped with go to greet.
// /version is mapped specifically to version.
http.HandleFunc("/", greet)
http.HandleFunc("/version", version)
http.HandleFunc("/user", userInfo)
log.Printf("serving http://%s\n", *addr)
log.Fatal(http.ListenAndServe(*addr, nil))
}
func version(w http.ResponseWriter, r *http.Request) {
info, ok := debug.ReadBuildInfo()
if !ok {
http.Error(w, "no build information available", 500)
return
}
fmt.Fprintf(w, "<!DOCTYPE html>\n<pre>\n")
fmt.Fprintf(w, "%s\n", html.EscapeString(info.String()))
}
func greet(w http.ResponseWriter, r *http.Request) {
name := strings.Trim(r.URL.Path, "/")
if name == "" {
name = "Gopher"
}
fmt.Fprintf(w, "<!DOCTYPE html>\n")
fmt.Fprintf(w, "%s, %s!\n", *greeting, html.EscapeString(name))
}
var users = map[string]string{
"alice": "Alice Smith",
"bob": "Bob Jones",
}
func userInfo(w http.ResponseWriter, r *http.Request) {
username := r.URL.Query().Get("name")
displayName := users[username]
// Bug: displayName is "" for unknown users, but we dereference
// a nil *http.Request later by shadowing r.
var detail *http.Request
fmt.Fprintf(w, "User: %s, Host: %s\n", displayName, detail.Host)
}