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
Advertisement
Something interesting
Tutorials
+10.1k Golang : Test a slice of integers for odd and even numbers
+5.4k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+5.7k Fix yum-complete-transaction error
+14k Golang : concatenate(combine) strings
+6.2k PHP : Get client IP address
+5.1k Golang : Check if a word is countable or not
+6.9k Fix sudo yum hang problem with no output or error messages
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+9k Golang : How to use Gorilla webtoolkit context package properly
+7.6k Javascript : Push notifications to browser with Push.js
+25.4k Golang : Generate MD5 checksum of a file
+12.2k Golang : calculate elapsed run time