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 (

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 {

(George Calianu) #3

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