http server go code example
Example 1: Golang HTTP Server
package main
import (
"fmt"
"log"
"net/http"
)
const (
Host = "localhost"
Port = "8080"
)
func home(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "This is a Simple HTTP Web Server!")
}
func main() {
http.HandleFunc("/", home)
err := http.ListenAndServe(Host+":"+Port, nil)
if err != nil {
log.Fatal("Error Starting the HTTP Server : ", err)
return
}
}
Example 2: http go
package main
import (
"fmt"
"net/http"
"time"
)
func greet(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello World! %s", time.Now())
}
func main() {
http.HandleFunc("/", greet)
http.ListenAndServe(":8080", nil)
}