Golang net/http.Handle(), HandleFunc() and ListenAndServe() functions examples

package net/http

Golang net/http.Handle(), HandleFunc() and ListenAndServe() functions usage examples

Example 1 :

 func main() {
 // http.Handler
 mux := http.NewServeMux()
 mux.HandleFunc("/", SayHelloWorld)
 mux.HandleFunc("/replyname", ReplyName)

 http.ListenAndServe(":8080", mux)
  }

Example 2:

 package main

 import (
 "log"
 "net/http"
 "time"
 )

 type timeHandler struct {
 format string
 }

 func (th *timeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 tm := time.Now().Format(th.format)
 w.Write([]byte("The time is: " + tm))
 }

 func main() {
 mux := http.NewServeMux()

 th := &timeHandler{format: time.RFC1123}
 mux.Handle("/time", th)

 log.Println("Listening...")
 http.ListenAndServe(":3000", mux)
 }

References :

http://golang.org/pkg/net/http/#Handle

http://golang.org/pkg/net/http/#HandleFunc

http://golang.org/pkg/net/http/#ListenAndServe

https://www.socketloop.com/tutorials/golang-http-server-example

http://www.alexedwards.net/blog/a-recap-of-request-handling

Advertisement