Skip to content

Commit

Permalink
Remove use of log in preference of Fprintf to stdout/stderr
Browse files Browse the repository at this point in the history
  • Loading branch information
brandur committed Aug 24, 2017
1 parent 3e23dab commit 19060b6
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 29 deletions.
31 changes: 18 additions & 13 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ package main
import (
"encoding/json"
"flag"
"log"
"fmt"
"net"
"net/http"
"os"
Expand All @@ -26,8 +26,6 @@ var version = "master"
// ---

func main() {
log.SetOutput(os.Stdout)

var showVersion bool
var port int
var unix string
Expand All @@ -38,58 +36,65 @@ func main() {
flag.Parse()

if showVersion || len(flag.Args()) == 1 && flag.Arg(0) == "version" {
log.Printf("%s\n", version)
fmt.Printf("%s\n", version)
return
}

if unix != "" && port != 0 {
flag.Usage()
log.Fatalf("Specify only one of -port or -unix")
fmt.Fprintf(os.Stderr, "Specify only one of -port or -unix\n")
os.Exit(1)
}

// Load the spec information from go-bindata
data, err := Asset("openapi/openapi/spec2.json")
if err != nil {
log.Fatalf("Error loading spec: %v", err)
fmt.Fprintf(os.Stderr, "Error loading spec: %v\n", err)
os.Exit(1)
}

var stripeSpec spec.Spec
err = json.Unmarshal(data, &stripeSpec)
if err != nil {
log.Fatalf("Error decoding spec: %v", err)
fmt.Fprintf(os.Stderr, "Error decoding spec: %v\n", err)
os.Exit(1)
}

// And do the same for fixtures
data, err = Asset("openapi/openapi/fixtures.json")
if err != nil {
log.Fatalf("Error loading fixtures: %v", err)
fmt.Fprintf(os.Stderr, "Error loading fixtures: %v\n", err)
os.Exit(1)
}

var fixtures spec.Fixtures
err = json.Unmarshal(data, &fixtures)
if err != nil {
log.Fatalf("Error decoding spec: %v", err)
fmt.Fprintf(os.Stderr, "Error decoding spec: %v\n", err)
os.Exit(1)
}

stub := StubServer{fixtures: &fixtures, spec: &stripeSpec}
err = stub.initializeRouter()
if err != nil {
log.Fatalf("Error initializing router: %v", err)
fmt.Fprintf(os.Stderr, "Error initializing router: %v\n", err)
os.Exit(1)
}

var listener net.Listener
if unix != "" {
listener, err = net.Listen("unix", unix)
log.Printf("Listening on unix socket %v", unix)
fmt.Printf("Listening on unix socket %v", unix)
} else {
if port == 0 {
port = defaultPort
}
listener, err = net.Listen("tcp", ":"+strconv.Itoa(port))
log.Printf("Listening on port %v", port)
fmt.Printf("Listening on port %v", port)
}
if err != nil {
log.Fatalf("Error listening on socket: %v", err)
fmt.Fprintf(os.Stderr, "Error listening on socket: %v\n", err)
os.Exit(1)
}

http.HandleFunc("/", stub.HandleRequest)
Expand Down
30 changes: 14 additions & 16 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"sort"
Expand Down Expand Up @@ -86,7 +85,7 @@ type stubServerRoute struct {
// HandleRequest handes an HTTP request directed at the API stub.
func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {
start := time.Now()
log.Printf("Request: %v %v", r.Method, r.URL.Path)
fmt.Printf("Request: %v %v\n", r.Method, r.URL.Path)

auth := r.Header.Get("Authorization")
if !validateAuth(auth) {
Expand All @@ -103,13 +102,13 @@ func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {

response, ok := route.method.Responses["200"]
if !ok {
log.Printf("Couldn't find 200 response in spec")
fmt.Printf("Couldn't find 200 response in spec\n")
writeResponse(w, r, start, http.StatusInternalServerError, nil)
return
}

if verbose {
log.Printf("Response schema: %+v", response.Schema)
fmt.Printf("Response schema: %+v\n", response.Schema)
}

var formString string
Expand All @@ -118,7 +117,7 @@ func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {
} else {
formBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("Couldn't read request body: %v", err)
fmt.Printf("Couldn't read request body: %v\n", err)
writeResponse(w, r, start, http.StatusInternalServerError, nil)
return
}
Expand All @@ -127,13 +126,13 @@ func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {
}
requestData, err := parser.ParseFormString(formString)
if err != nil {
log.Printf("Couldn't parse query/body: %v", err)
fmt.Printf("Couldn't parse query/body: %v\n", err)
writeResponse(w, r, start, http.StatusInternalServerError, nil)
return
}

if verbose {
log.Printf("Request data: %+v", requestData)
fmt.Printf("Request data: %+v\n", requestData)
}

// OpenAPI 2.0 stores a possible JSON schema in a special parameter that's
Expand All @@ -143,12 +142,11 @@ func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {
// support validation all verbs, and much more simply.
requestSchema := bodyParameterSchema(route.method)
if requestSchema != nil {
log.Printf("requestSchema = %+v\n", requestSchema)
coercer.CoerceParams(requestSchema, requestData)

err := route.validator.Validate(requestData)
if err != nil {
log.Printf("Validation error: %v", err)
fmt.Printf("Validation error: %v\n", err)
responseData := fmt.Sprintf("Request error: %v", err)
writeResponse(w, r, start, http.StatusBadRequest, responseData)
return
Expand All @@ -157,13 +155,13 @@ func (s *StubServer) HandleRequest(w http.ResponseWriter, r *http.Request) {

expansions, rawExpansions := extractExpansions(requestData)
if verbose {
log.Printf("Expansions: %+v", rawExpansions)
fmt.Printf("Expansions: %+v\n", rawExpansions)
}

generator := DataGenerator{s.spec.Definitions, s.fixtures}
responseData, err := generator.Generate(response.Schema, r.URL.Path, expansions)
if err != nil {
log.Printf("Couldn't generate response: %v", err)
fmt.Printf("Couldn't generate response: %v\n", err)
writeResponse(w, r, start, http.StatusInternalServerError, nil)
return
}
Expand All @@ -183,7 +181,7 @@ func (s *StubServer) initializeRouter() error {
pathPattern := compilePath(path)

if verbose {
log.Printf("Compiled path: %v", pathPattern.String())
fmt.Printf("Compiled path: %v\n", pathPattern.String())
}

for verb, method := range verbs {
Expand Down Expand Up @@ -214,7 +212,7 @@ func (s *StubServer) initializeRouter() error {
}
}

log.Printf("Routing to %v path(s) and %v endpoint(s) with %v validator(s)",
fmt.Printf("Routing to %v path(s) and %v endpoint(s) with %v validator(s)\n",
numPaths, numEndpoints, numValidators)
return nil
}
Expand Down Expand Up @@ -328,7 +326,7 @@ func writeResponse(w http.ResponseWriter, r *http.Request, start time.Time, stat
}

if err != nil {
log.Printf("Error serializing response: %v", err)
fmt.Printf("Error serializing response: %v\n", err)
writeResponse(w, r, start, http.StatusInternalServerError, nil)
return
}
Expand All @@ -338,9 +336,9 @@ func writeResponse(w http.ResponseWriter, r *http.Request, start time.Time, stat
w.WriteHeader(status)
_, err = w.Write(encodedData)
if err != nil {
log.Printf("Error writing to client: %v", err)
fmt.Printf("Error writing to client: %v\n", err)
}
log.Printf("Response: elapsed=%v status=%v", time.Now().Sub(start), status)
fmt.Printf("Response: elapsed=%v status=%v\n", time.Now().Sub(start), status)
}

func validateAuth(auth string) bool {
Expand Down

0 comments on commit 19060b6

Please sign in to comment.