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
+22.9k Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
+3.7k MariaDB/MySQL : How to get version information
+18k Golang : Check if directory exist and create if does not exist
+4.8k Unix/Linux : Get reboot history or check when was the last reboot date
+5.1k Golang : Experimenting with the Rejang script
+10.6k Golang : Handle API query by curl with Gorilla Queries example
+3.9k Golang : A program that contain another program and executes it during run-time
+7k Golang : Add build version and other information in executables
+13.6k Golang : Accurate and reliable decimal calculations
+5.4k Golang : Convert an executable file into []byte example
+13.2k Golang : On enumeration
+9.6k Golang : Get UDP client IP address and differentiate clients by port number