Golang : HTTP Server Example
Simple tutorial on HTTP server examples with Golang. Run the codes below and point your browser to http://localhost:8080
or http://localhost:8080/replyname/yourname
for example 2.
Example 1:
package main
import (
"net/http"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
html := "Hello"
html = html + " World"
w.Write([]byte(html))
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
http.ListenAndServe(":8080", mux)
}
Example 2:
package main
import (
"net/http"
"strings"
)
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
}
func ReplyName(w http.ResponseWriter, r *http.Request) {
URISegments := strings.Split(r.URL.Path, "/")
w.Write([]byte(URISegments[1]))
}
func main() {
// http.Handler
mux := http.NewServeMux()
mux.HandleFunc("/", SayHelloWorld)
mux.HandleFunc("/replyname", ReplyName)
http.ListenAndServe(":8080", mux)
}
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.4k Golang : Rot13 and Rot5 algorithms example
+25.5k Golang : Daemonizing a simple web server process example
+15.1k Golang : How to add color to string?
+6.4k Unix/Linux : How to get own IP address ?
+5.9k nginx : force all pages to be SSL
+8.6k Golang : Find duplicate files with filepath.Walk
+32.1k Golang : Math pow(the power of x^y) example
+62.5k Golang : Convert HTTP Response body to string
+25.9k Mac/Linux and Golang : Fix bind: address already in use error
+7.4k Golang : Get YouTube playlist
+19.2k Golang : Fix cannot download, $GOPATH not set error
+11.9k Golang : Sort and reverse sort a slice of runes