Skip to content

Conversation

@fharding1
Copy link
Contributor

Clarify in documentation that SetURLVars does not modify the given *htttp.Request, provide an example of usage.

Addresses #334

Clarify in documentation that SetURLVars does not modify the given
*htttp.Request, provide an example of usage.
@kisielk
Copy link
Contributor

kisielk commented Jan 20, 2018

Can you make the example a runnable example test? The function doc can be shorter, just "... does not modify its arguments, but returns a shallow copy..", it should be obvious that it can be assigned to something.

@fharding1
Copy link
Contributor Author

fharding1 commented Jan 20, 2018

Sure! Just to clarify, would you want me to include package, imports, etc, or just the relevant parts, like

package example

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gorilla/mux"
	"github.com/stretchr/testify/assert"
)

const (
	varKey   = "foo"
	varValue = "bar"
)

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(mux.Vars(r)[varKey]))
}

func TestExample(t *testing.T) {
	req, _ := http.NewRequest("GET", "/foo", nil)
	req = mux.SetURLVars(req, map[string]string{varKey: varValue})
	rr := httptest.NewRecorder()

	ExampleHandler(rr, req)

	assert.Equal(t, varValue, string(rr.Body.Bytes()))
}

vs

const (
	varKey   = "foo"
	varValue = "bar"
)

func ExampleHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte(mux.Vars(r)[varKey]))
}

func TestExample(t *testing.T) {
	req, _ := http.NewRequest("GET", "/foo", nil)
	req = mux.SetURLVars(req, map[string]string{varKey: varValue})
	rr := httptest.NewRecorder()

	ExampleHandler(rr, req)

	assert.Equal(t, varValue, string(rr.Body.Bytes()))
}

@kisielk
Copy link
Contributor

kisielk commented Jan 20, 2018

Make a function in one of the test files called ExampleSetURLVars and put the whole example in there. That will show up in the documentation alongside the SetURLVars function. More details in the "Examples" section here: https://godoc.org/testing

@fharding1
Copy link
Contributor Author

fharding1 commented Jan 20, 2018

Added. It's my first time using example test functions, so I apologize if I messed up.

@kisielk kisielk merged commit 0fdf828 into gorilla:master Jan 20, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants