Created
December 6, 2017 09:46
-
-
Save s-l-teichmann/9e4561e7582c1a2de850361e6758705b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Small example how to do a web server in Go with stdlib. | |
// (c) 2017 by Sascha L. Teichmann | |
// The is Free Software covered by the terms of the MIT License. | |
// See https://opensource.org/licenses/MIT for details. | |
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"net/http" | |
) | |
type controller struct { | |
name string | |
allNames []string | |
} | |
func (c *controller) handler(rw http.ResponseWriter, req *http.Request) { | |
ctx := req.Context() | |
name := ctx.Value("user").(string) | |
fmt.Printf("user: %s\n", name) | |
fmt.Fprintf(rw, "Hello %s %s\n", c.name, name) | |
} | |
func (c *controller) handler2(rw http.ResponseWriter, req *http.Request) { | |
fmt.Fprintf(rw, "Helloooooo %s\n", c.name) | |
for _, n := range c.allNames { | |
fmt.Fprintf(rw, "Helloooooo %s\n", n) | |
} | |
} | |
func middleware(fn http.Handler) http.Handler { | |
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { | |
fmt.Println("Before") | |
ctx := req.Context() | |
// Do something more fancy here. | |
ctx = context.WithValue(ctx, "user", "from_middleware") | |
req = req.WithContext(ctx) | |
fn.ServeHTTP(rw, req) | |
}) | |
} | |
func main() { | |
c := controller{name: "Peter", allNames: []string{"Jürgen", "Otto", "Claudia"}} | |
mux := http.NewServeMux() | |
mux.Handle("/index", middleware(http.HandlerFunc(c.handler))) | |
mux.Handle("/hello", http.HandlerFunc(c.handler2)) | |
log.Fatalf("error: %v\n", http.ListenAndServe("localhost:8080", mux)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment