Saturday 4 September 2021

Go HTTP Server

Go can be also used to create web applications. Net/http is a library package used to build web applications. 

It has HandelFunc() function which routes the incoming request to its corresponding function. 

The ListenAndServe function is used to create a resource server which listens to the provided port. The function someFunc has the http.ResponceWriter and http.Request type parameter. 

It is responsible to take the incoming request and after processing the return response.

Go http server example

  1.       
  2. package main  
  3. import (  
  4.    "fmt"  
  5.    "net/http"  
  6. )  
  7. func main() {  
  8.    http.HandleFunc("/",MyHandler1)  
  9.    http.HandleFunc("/John",MyHandler2)  
  10.    http.ListenAndServe(":8080",nil)  
  11. }  
  12. func MyHandler1(w http.ResponseWriter,r *http.Request){  
  13.    fmt.Fprint(w,"Hello World\n")  
  14. }  
  15. func MyHandler2(w http.ResponseWriter,r *http.Request){  
  16.    fmt.Fprint(w,"Hello John\n")  
  17. }  

Output:

GO Http server 1

No comments:

Post a Comment