Why I cannot do ListenAndServe from main function


(Gowtham Girithar) #1

Hi All,

why I cannot do http listen in main function?

func main() {
//handleallRequests() // enable this line and disable next line works
http.ListenAndServe(“8081” , nil) -> this is not working - program exit
}

func handleallRequests() {
http.ListenAndServe(":8081", nil) -> this is working
}


(Boban Acimovic) #2

You have no handler (nil). Try this:

package main

import (
	"fmt"
	"net/http"
)

type CustomHandler int

func (handler CustomHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	fmt.Println("the handler")
}

func main() {
	var handler CustomHandler
	err := http.ListenAndServe(":8081" , handler)
	if err != nil {
		panic(err)
	}
}

(George Calianu) #3

http.ListenAndServe expect an address and a port, eg. :8081 mean localhost:8081. You wrote just 8081 wich is wrong.


(Ram Mohan) #4

your statements in main and handleallRequests functions are not same .
http.ListenAndServe(“8081” , nil) -> this is not working - program exit
http.ListenAndServe(":8081", nil) -> this is working

ListenAndServe method expects IP:PORT string, if you dont want to specify IP you can just mention “:PORT” in main function you are missing “:” and in other function you are using “:”. this is why you are not successfully starting server from main.

you can wrap this code in log.Println(http.ListenAndServe(":8081", nil)) so that instantly you can get to know the error !!!