Created
April 24, 2017 20:07
-
-
Save cybersiddhu/3b0f1964e1022afe2b1ac319a18ff0dc to your computer and use it in GitHub Desktop.
golang webapp example
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
package main | |
import ( | |
"context" | |
"fmt" | |
"log" | |
"math/rand" | |
"net/http" | |
"os" | |
"time" | |
"github.com/dictyBase/go-middlewares/middlewares/logrus" | |
"github.com/rs/cors" | |
"gopkg.in/codegangsta/cli.v1" | |
) | |
func main() { | |
app := cli.NewApp() | |
app.Name = "routertest" | |
app.Usage = "Test the httprouter with net/http wrapping" | |
app.Version = "1.0.0" | |
app.Flags = []cli.Flag{ | |
cli.IntFlag{ | |
Name: "port, p", | |
Usage: "server port", | |
Value: 9998, | |
}, | |
} | |
app.Action = TestRouterAction | |
app.Run(os.Args) | |
} | |
func TestRouterAction(c *cli.Context) error { | |
r := NewRouter() | |
cr := cors.New(cors.Options{ | |
AllowedOrigins: []string{"*"}, | |
AllowCredentials: true, | |
OptionsPassthrough: true, | |
Debug: true, | |
}) | |
lchain := NewChain(logrus.NewLogger().LoggerMiddlewareFn) | |
r.Get("/whisky/:brand", lchain.ThenFunc(WhiskyHandler)) | |
r.Get("/exercise/:name", lchain.Append(CorsAdapter(cr), InjectSetsMiddle).ThenFunc(ExerciseHandler)) | |
log.Printf("Starting web server on port %d\n", c.Int("port")) | |
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", c.Int("port")), r.Router)) | |
return nil | |
} | |
// middlewares | |
func InjectSetsMiddle(fn http.HandlerFunc) http.HandlerFunc { | |
nfn := func(w http.ResponseWriter, r *http.Request) { | |
rd := rand.New(rand.NewSource(time.Now().UnixNano())) | |
ctx := context.WithValue(r.Context(), "sets", rd.Intn(10)) | |
fn(w, r.WithContext(ctx)) | |
} | |
return nfn | |
} | |
// final handlers | |
func WhiskyHandler(w http.ResponseWriter, r *http.Request) { | |
params := Params(r) | |
fmt.Fprintf(w, "I love whisky %s!\n", params.ByName("brand")) | |
} | |
func ExerciseHandler(w http.ResponseWriter, r *http.Request) { | |
sets, ok := r.Context().Value("sets").(int) | |
if !ok { | |
http.Error(w, "unable to retrieve context", http.StatusInternalServerError) | |
return | |
} | |
fmt.Fprintf(w, "I Love doing %s exercise! for %d sets\n", Params(r).ByName("name"), sets) | |
} | |
func CorsAdapter(c *cors.Cors) MiddlewareFn { | |
fn := func(fn http.HandlerFunc) http.HandlerFunc { | |
ifn := func(w http.ResponseWriter, r *http.Request) { | |
c.HandlerFunc(w, r) | |
fn(w, r) | |
} | |
return ifn | |
} | |
return fn | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment