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
+5.8k Golang : How to call function inside template with template.FuncMap
+9.9k Use systeminfo to find out installed Windows Hotfix(s) or updates
+15.1k Golang : Convert slice to array
+17.5k Golang : Calculate entire request body length during run time
+8.6k Golang : Sort and reverse sort a slice of floats
+6.5k Golang : Gorrila set route name and get the current route name
+8.9k Golang : Print how to use flag for your application example
+5k Golang : Scan forex opportunities by Bollinger bands
+19.7k Golang : How to get time zone and load different time zone?
+12k Golang : Read from buffered reader until specific number of bytes
+8.5k Golang : Turn string or text file into slice example
+5.1k Golang : Selection sort example