Create Simple Server in Golang

In this post we will discuss about golang’s simple server#

golang have very good support for web server. golang net/http package have all the functionality required for creating full featured web api

we will use net/http package to write a simple web server

first create a main package with main function which is main entry point for program to start

our code will look like below


package main

func main() {

}

now import the net/http package

import "net/http"

our server will contain one simple handler wich will simply return Hello From Golang

there is function called ListenAndServe(":3000") in http package will start our server and listen on port 3000

we will create a simple handler function that will serve any request

structure for that handler will look like this

func(w http.ResponseWriter, r *http.Request) {

}

any function have above structure can works as handler

package main
import "net/http"
import "fmt"

func main() {

http.HandleFunc("/",func(w http.ResponseWriter, r *http.Request){

	fmt.FPrintf(w,[]byte("Hello from golang"))

})

http.ListenAndServe(":3000",nil)
	
}

comments powered by Disqus