Using custom URL for httptest.NewServer in Go


I am running UT on some rest calls by creating a http test server in the Go language. My code is as follows.

type student struct{
FirstName string
LastName string

func testGetStudentName() {
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    response = new(student)
    response.FirstName = "Some"
    response.LastName = "Name"
    b, err := json.Marshal(response)
    if err == nil {
            fmt.Fprintln(w, string(b[:]))
    defer ts.Close()
    student1 := base.getStudent("123")
    log.Print("testServerUrl",testServer.URL) //prints out ( port changes every time this is run)

   ts.URL = "" //this assignment does not quite change the URL of the created test server.

In the file being tested,

var baseURL = ""
var mockUrl = ""
func Init(mockServer bool){
    if mockServer {
        baseURL = mockUrl

func getStudent(id String){
     url := baseUrl + "/student/" + id
     req, err := http.NewRequest("GET", url, nil)

This init is called from my test.

This creates a new test server and runs the calls on a random port. Is it possible for me to run this server on a port I specify?


Most applications use the port assigned in NewServer or NewUnstartedServer because this port will not conflict with a port in use on the machine. Instead of assigning a port, they set the base URL for the service to the test server’s URL.

If you do want to set the listening port, do the following:

// create a listener with the desired port.
l, err := net.Listen("tcp", "")
if err != nil {

ts := httptest.NewUnstartedServer(handler)

// NewUnstartedServer creates a listener. Close that listener and replace 
// with the one we created.
ts.Listener = l

// Start the server.
// Stop the server on return from the function.  
defer ts.Stop()

// Add your test code here.  

Answered By – Bayta Darell

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.