Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Go 1.7 context #41

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
language: go

go:
- 1.4
- tip
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why tip?


before_install:
- go install -a -race std
Expand Down
46 changes: 11 additions & 35 deletions example/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package main

import (
"errors"
"fmt"
"io/ioutil"
"net/http"

"github.com/gorilla/mux"
"github.com/remind101/pkg/httpx"
"github.com/remind101/pkg/httpx/middleware"
"github.com/remind101/pkg/logger"
Expand All @@ -14,66 +14,42 @@ import (
"golang.org/x/net/context"
)

func ok(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
func ok(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()

ip, err := ip(ctx)
if err != nil {
return err
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

logger.Info(ctx, "ip address", "ip", ip)

_, err = fmt.Fprintf(w, "%s\n", ip)
return err
}

func bad(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return &Error{ID: "bad_error", Err: errors.New("bad request")}
}

func boom(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
panic("boom")
}

func errorHandler(ctx context.Context, err error, w http.ResponseWriter, r *http.Request) {
http.Error(w, err.Error(), http.StatusInternalServerError)
fmt.Fprintf(w, "%s\n", ip)
}

func main() {
// An error reporter that will log errors to stdout.
r := reporter.NewLogReporter()

m := httpx.NewRouter()
m := mux.NewRouter()

m.HandleFunc("/ok", ok).Methods("GET")
m.HandleFunc("/bad", bad).Methods("GET")
m.HandleFunc("/boom", boom).Methods("GET")
m.Handle("/auth", middleware.BasicAuth(httpx.HandlerFunc(ok), "user", "pass", "realm")).Methods("GET")
m.Handle("/auth", middleware.BasicAuth(http.HandlerFunc(ok), "user", "pass", "realm")).Methods("GET")

var h httpx.Handler
var h http.Handler

// Recover from panics, and report the recovered error to the reporter.
h = middleware.Recover(m, r)

// Handles any errors returned from handlers in a common format.
h = middleware.HandleError(h, errorHandler)

// Adds a logger to the context.Context that will log to stdout,
// prefixed with the request id.
h = middleware.LogTo(h, middleware.StdoutLogger)

// Adds the request id to the context.
h = middleware.ExtractRequestID(h)

http.ListenAndServe(":8080", middleware.BackgroundContext(h))
}

type Error struct {
ID string
Err error
}

func (e *Error) Error() string {
return fmt.Sprintf("%s: %s", e.ID, e.Err)
http.ListenAndServe(":8080", h)
}

// ip returns your ip.
Expand Down
3 changes: 1 addition & 2 deletions httpx/http_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package httpx

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
Expand All @@ -12,8 +13,6 @@ import (
"time"

"github.com/remind101/pkg/retry"

"golang.org/x/net/context"
)

type RoundTripper interface {
Expand Down
2 changes: 1 addition & 1 deletion httpx/http_service_test.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
package httpx

import (
"context"
"io/ioutil"
"net/http"
"net/url"
"strings"
"testing"

"golang.org/x/net/context"
"github.com/remind101/pkg/retry"
)

Expand Down
22 changes: 0 additions & 22 deletions httpx/httpx.go
Original file line number Diff line number Diff line change
@@ -1,28 +1,6 @@
// package httpx provides an extra layer of convenience over package http.
package httpx

import (
"net/http"

"golang.org/x/net/context"
)

// Handler is represents a Handler that can take a context.Context as the
// first argument.
type Handler interface {
ServeHTTPContext(context.Context, http.ResponseWriter, *http.Request) error
}

// The HandlerFunc type is an adapter to allow the use of ordinary functions as
// httpx handlers. If f is a function with the appropriate signature,
// HandlerFunc(f) is a Handler object that calls f.
type HandlerFunc func(context.Context, http.ResponseWriter, *http.Request) error

// ServeHTTPContext calls f(ctx, w, r)
func (f HandlerFunc) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return f(ctx, w, r)
}

// key used to store context values from within this package.
type key int

Expand Down
43 changes: 0 additions & 43 deletions httpx/middleware/background.go

This file was deleted.

33 changes: 0 additions & 33 deletions httpx/middleware/background_test.go

This file was deleted.

20 changes: 8 additions & 12 deletions httpx/middleware/basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,18 @@ import (
"fmt"
"net/http"
"strings"

"github.com/remind101/pkg/httpx"
"golang.org/x/net/context"
)

type BasicAuther struct {
User, Pass string
Realm string

// The handler that will be called if the request is authorized.
Handler httpx.Handler
Handler http.Handler

// The handler that will be called if the request is not authorized. The
// zero value is DefaultUnauthorizedHandler
UnauthorizedHandler httpx.Handler
UnauthorizedHandler http.Handler
}

func (a *BasicAuther) authenticated(r *http.Request) bool {
Expand All @@ -40,27 +37,26 @@ func (a *BasicAuther) authenticated(r *http.Request) bool {
return a.User == pair[0] && a.Pass == pair[1]
}

func DefaultUnauthorizedHandler(realm string) httpx.HandlerFunc {
return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
func DefaultUnauthorizedHandler(realm string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm=%q`, realm))
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return nil
})
}

func (a *BasicAuther) ServeHTTPContext(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
func (a *BasicAuther) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if a.authenticated(r) {
return a.Handler.ServeHTTPContext(ctx, w, r)
a.Handler.ServeHTTP(w, r)
} else {
u := a.UnauthorizedHandler
if u == nil {
u = DefaultUnauthorizedHandler(a.Realm)
}
return u.ServeHTTPContext(ctx, w, r)
u.ServeHTTP(w, r)
}
}

func BasicAuth(h httpx.Handler, user, pass, realm string) *BasicAuther {
func BasicAuth(h http.Handler, user, pass, realm string) *BasicAuther {
return &BasicAuther{
User: user,
Pass: pass,
Expand Down
23 changes: 6 additions & 17 deletions httpx/middleware/basic_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,54 +4,43 @@ import (
"net/http"
"net/http/httptest"
"testing"

"github.com/remind101/pkg/httpx"
"golang.org/x/net/context"
)

func TestBasicAuth(t *testing.T) {
ctx := context.Background()
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/city/123.123.123.123", nil)
req.SetBasicAuth("user", "pass")

var h httpx.Handler
var h http.Handler

const test_str = "sfaftfofsfhfi"

h = httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(test_str))
return nil
})

h = BasicAuth(h, "user", "pass", "realm")
if err := h.ServeHTTPContext(ctx, resp, req); err != nil {
t.Fatal(err)
}
h.ServeHTTP(resp, req)

if got, want := resp.Body.String(), test_str; got != want {
t.Fatalf("Body => %s; want %s", got, want)
}
}

func TestBasicAuthUnauthorized(t *testing.T) {
ctx := context.Background()
resp := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/city/123.123.123.123", nil)

var h httpx.Handler
var h http.Handler

const test_str = "sfaftfofsfhfi"

h = httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
h = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(test_str))
return nil
})

h = BasicAuth(h, "user", "pass", "realm")
if err := h.ServeHTTPContext(ctx, resp, req); err != nil {
t.Fatal(err)
}
h.ServeHTTP(resp, req)

if resp.Code != 401 {
t.Fatalf("Expected code 401")
Expand Down
Loading