1 // Copyright 2009 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.
23 // hello world, the web server
24 var helloRequests
= expvar
.NewInt("hello-requests")
26 func HelloServer(w http
.ResponseWriter
, req
*http
.Request
) {
28 io
.WriteString(w
, "hello, world!\n")
31 // Simple counter server. POSTing to it will set the value.
33 mu sync
.Mutex
// protects n
37 // This makes Counter satisfy the expvar.Var interface, so we can export
39 func (ctr
*Counter
) String() string {
42 return fmt
.Sprintf("%d", ctr
.n
)
45 func (ctr
*Counter
) ServeHTTP(w http
.ResponseWriter
, req
*http
.Request
) {
52 buf
:= new(bytes
.Buffer
)
53 io
.Copy(buf
, req
.Body
)
55 if n
, err
:= strconv
.Atoi(body
); err
!= nil {
56 fmt
.Fprintf(w
, "bad POST: %v\nbody: [%v]\n", err
, body
)
59 fmt
.Fprint(w
, "counter reset\n")
62 fmt
.Fprintf(w
, "counter = %d\n", ctr
.n
)
66 var booleanflag
= flag
.Bool("boolean", true, "another flag for testing")
68 func FlagServer(w http
.ResponseWriter
, req
*http
.Request
) {
69 w
.Header().Set("Content-Type", "text/plain; charset=utf-8")
70 fmt
.Fprint(w
, "Flags:\n")
71 flag
.VisitAll(func(f
*flag
.Flag
) {
72 if f
.Value
.String() != f
.DefValue
{
73 fmt
.Fprintf(w
, "%s = %s [default = %s]\n", f
.Name
, f
.Value
.String(), f
.DefValue
)
75 fmt
.Fprintf(w
, "%s = %s\n", f
.Name
, f
.Value
.String())
80 // simple argument server
81 func ArgServer(w http
.ResponseWriter
, req
*http
.Request
) {
82 for _
, s
:= range os
.Args
{
87 // a channel (just for the fun of it)
90 func ChanCreate() Chan
{
100 func (ch Chan
) ServeHTTP(w http
.ResponseWriter
, req
*http
.Request
) {
101 io
.WriteString(w
, fmt
.Sprintf("channel send #%d\n", <-ch
))
104 // exec a program, redirecting output
105 func DateServer(rw http
.ResponseWriter
, req
*http
.Request
) {
106 rw
.Header().Set("Content-Type", "text/plain; charset=utf-8")
108 date
, err
:= exec
.Command("/bin/date").Output()
110 http
.Error(rw
, err
.Error(), 500)
116 func Logger(w http
.ResponseWriter
, req
*http
.Request
) {
118 http
.Error(w
, "oops", 404)
121 var webroot
= flag
.String("root", os
.Getenv("HOME"), "web root directory")
126 // The counter is published as a variable directly.
128 expvar
.Publish("counter", ctr
)
129 http
.Handle("/counter", ctr
)
130 http
.Handle("/", http
.HandlerFunc(Logger
))
131 http
.Handle("/go/", http
.StripPrefix("/go/", http
.FileServer(http
.Dir(*webroot
))))
132 http
.Handle("/chan", ChanCreate())
133 http
.HandleFunc("/flags", FlagServer
)
134 http
.HandleFunc("/args", ArgServer
)
135 http
.HandleFunc("/go/hello", HelloServer
)
136 http
.HandleFunc("/date", DateServer
)
137 err
:= http
.ListenAndServe(":12345", nil)
139 log
.Panicln("ListenAndServe:", err
)