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
+7k Golang : Calculate BMI and risk category
+23.7k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+4.4k Javascript : How to show different content with noscript?
+12k Golang : Convert decimal number(integer) to IPv4 address
+8.1k Golang : Sort words with first uppercase letter
+10k Golang : Check if user agent is a robot or crawler example
+8.9k Golang : HTTP Routing with Goji example
+13.6k Golang : Strings comparison
+13.5k Golang : Generate Code128 barcode
+9.7k Golang : How to extract video or image files from html source code
+14.1k Golang : convert rune to unicode hexadecimal value and back to rune character
+26.2k Golang : Convert IP address string to long ( unsigned 32-bit integer )