Why I cannot do ListenAndServe from main function

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
}

2 Likes

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)
	}
}
2 Likes

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

3 Likes

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 !!!

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.